2013-04-11 62 views
5

我要定义一个类型是这样的(类型* S的指数):无效操作:S [k]的

type S map[string]interface{} 

,我想一个方法添加到这样的类型:

func (s *S) Get(k string) (interface {}){ 
    return s[k] 
} 

当程序运行时,出现了这样的错误:

invalid operation: s[k] (index of type *S) 

那么,如何定义类型和方法添加到类型?

回答

10

例如,

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] 
+3

也许阐述上指针位VS值接收器,为什么地图可以用一个值传感器工作吗? – cthom06 2013-04-11 02:48:35