例如,
package main
import "fmt"
type S map[string]interface{}
func (s *S) Get(k string) interface{} {
return (*s)[k]
}
func main() {
s := S{"t": int(42)}
fmt.Println(s)
t := s.Get("t")
fmt.Println(t)
}
输出:
map[t:42]
42
地图是参考的类型,其含有一个指向基础映射,所以你通常不会需要使用一个指针s
。我已经添加了一个方法来强调这一点。例如,
package main
import "fmt"
type S map[string]interface{}
func (s S) Get(k string) interface{} {
return s[k]
}
func (s S) Put(k string, v interface{}) {
s[k] = v
}
func main() {
s := S{"t": int(42)}
fmt.Println(s)
t := s.Get("t")
fmt.Println(t)
s.Put("K", "V")
fmt.Println(s)
}
输出:
map[t:42]
42
map[t:42 K:V]
也许阐述上指针位VS值接收器,为什么地图可以用一个值传感器工作吗? – cthom06 2013-04-11 02:48:35