Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Golang maps are reference types
package main
import "fmt"
// Function tp update maps
func updateNumbers(m map[string]int) {
m["three"] = 3
m["four"] = 4
func main() {
veggies := map[string]int{
"onion": 12,
"cabbage": 15,
veggies["orka"] = 90
// Returns Original veggies map map[onion:12 cabbage:15 orka:90]
fmt.Println("Original veggies map", veggies)
newVeggies := veggies
newVeggies["orka"] = 180
// Returns New Veggies map map[cabbage:15 orka:180 onion:12]
fmt.Println("New Veggies map", newVeggies)
// Returns Updated veggies map[onion:12 cabbage:15 orka:180]
fmt.Println("Updated veggies", veggies)
// Passing map to a function
numbers := make(map[string]int)
numbers["one"] = 1
numbers["two"] = 2
// Returns numbers map[one:1 two:2]
fmt.Println("numbers", numbers)
// Add elements to the map in the function
// Returns after numbers are updated map[one:1 two:2 three:3 four:4]
fmt.Println("after numbers are updated", numbers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment