可以在`map[string]interface{}`上定义一个函数吗?

huangapple go评论72阅读模式
英文:

can I define a function on a map[string]interface{}

问题

我已经尝试了以下两种方式:

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

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

但是在运行go test时出现了错误:

invalid receiver type map[string]interface {} (map[string]interface {} is an unnamed type)

所以我需要添加一些额外的文本来让 SO(Stack Overflow)满意。

英文:

I have tried

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

and

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

but go test errors with

invalid receiver type map[string]interface {} (map[string]interface {} is an unnamed type)

so I have to add some more text to keep SO happy here

答案1

得分: 6

你需要定义一个新的类型,以便能够附加一个方法到它上面。

package main

import "fmt"

type MyMap map[string]interface{}

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

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

请注意,这是一个示例代码,它定义了一个名为MyMap的类型,并在该类型上定义了一个名为Foo的方法。在main函数中,我们创建了一个MyMap类型的实例m,并调用了Foo方法。当运行这段代码时,它会打印出"You fool!"。

英文:

You need to define a new type to be able to attach a method to it.

package main

import "fmt"

type MyMap map[string]interface{}

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

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

huangapple
  • 本文由 发表于 2014年5月23日 08:05:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/23819032.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定