例如,
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