我可以在地图上定义一个函数[string] interface {}

时间:2014-05-23 00:06:00

标签: go

我试过了

 func (m map[string]interface{}) Foo() {
     ...
    }

 func (m *map[string]interface{}) Foo() {
     ...
    }

但是用

来测试错误
invalid receiver type map[string]interface {} (map[string]interface {} is an unnamed type)

所以我必须添加更多文字以保持这里的快乐

1 个答案:

答案 0 :(得分:5)

您需要定义一个新类型才能将方法附加到它。

package main

import "fmt"

type MyMap map[string]interface{}

func (m MyMap) Foo() {
        fmt.Println("You fool!")
}

func main(){
  m := new(MyMap)
  m.Foo()
}