package main
import "fmt"
func mapToAnotherFunction(m map[string]int) {
m["hello"] = 3
m["world"] = 4
m["new_word"] = 5
}
// func mapToAnotherFunctionAsRef(m *map[string]int) {
// m["hello"] = 30
// m["world"] = 40
// m["2ndFunction"] = 5
// }
func main() {
m := make(map[string]int)
m["hello"] = 1
m["world"] = 2
// Initial State
for key, val := range m {
fmt.Println(key, "=>", val)
}
fmt.Println("-----------------------")
mapToAnotherFunction(m)
// After Passing to the function as a pointer
for key, val := range m {
fmt.Println(key, "=>", val)
}
// Try Un Commenting This Line
fmt.Println("-----------------------")
// mapToAnotherFunctionAsRef(&m)
// // After Passing to the function as a pointer
// for key, val := range m {
// fmt.Println(key, "=>", val)
// }
// Outputs
// prog.go:12:4: invalid operation: m["hello"] (type *map[string]int does not support indexing)
// prog.go:13:4: invalid operation: m["world"] (type *map[string]int does not support indexing)
// prog.go:14:4: invalid operation: m["2ndFunction"] (type *map[string]int does not support indexing)
}
3 回答
在这个主题中你会找到你的答案:
Golang: Accessing a map using its reference
默认情况下,没有 Map 参考 .
来自Golang博客 -
m = make(map[string]int)
Code Snippet Link玩它 .
以下是Dave Chaney发自If a map isn’t a reference variable, what is it?的部分内容:
和结论:
关于
map
语法的历史/解释: