Created
February 18, 2019 15:45
-
-
Save cjgiridhar/c5ed22ff03f9a942f67f5e7d1d1ec42e to your computer and use it in GitHub Desktop.
Golang maps are reference types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
updateNumbers(numbers) | |
// 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