Create method for map[string]interface{} in Go

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

Create method for map[string]interface{} in Go

问题

我已经定义了一个类型:

type UnknownMapString map[string]interface{}

我还为它们定义了一些方法,如下所示:

func (m UnknownMapString) Foo() {
    fmt.Println("test!")
}

当我运行时出现了一个恐慌:

接口转换:接口是map[string]interface{},而不是main.UnknownMapString

map[string]interface{} 是从 JSON 输入中解组的。

在这个例子中,我认为你不能将接口作为方法的接收者,所以我们需要进行类型断言(而不是转换),将其转换为一个具名类型,并将该具名类型用作方法的接收者。
请告诉我我做错了什么。谢谢!

英文:

I have defined a Type

type UnknownMapString map[string]interface{}

I also have methods for them like so

func (m UnknownMapString) Foo() {
    fmt.Println("test!")
}

I get a panic when running:

> interface conversion: interface is map[string]interface {}, not
> main.UnknownMapString

The map[string]interface{} is unmarshaled from JSON input.

Playground replicating it -> http://play.golang.org/p/kvw4dcZVNH

I thought that you could not have interface as a receiver of method so we needed to type assert (not convert?) to a Named Type and use that Named Type as the receiver of the method.
Please let me know what I'm doing wrong. Thanks!

答案1

得分: 5

val = val.(UnknownMapString)

这是一个类型断言(type assertion),它假设命名类型(named type)UnknownMapString 与未命名类型 map[string]interface{} 相同。
而类型一致性(type identity)告诉我们:

命名类型和未命名类型始终不同。

但是:你可以将 map[string]interface{} 赋值给 UnknownMapString,因为

x 的类型 VT 具有相同的底层类型,并且 VT 中至少有一个不是命名类型时,x 可以赋值给类型 T("x 可以赋值给 T")。

这将起作用:

var val2 UnknownMapString = val.(map[string]interface{})
val2.Foo()

val2 不是未命名类型,而且 val2val.(map[string]interface{}) 的底层类型是相同的。

输出:

test!

play.golang.org

英文:
val = val.(UnknownMapString)

This is a type assertion, which supposes the named type UnknownMapString is identical to the unnamed type map[string]interface{}.
And type identity tells us that:

> A named and an unnamed type are always different.

But: you can **assign** a map[string]interface{} to a UnknownMapString because

> x is assignable to a variable of type T ("x is assignable to T") when:

> x's type V and T have identical underlying types and at least one of V or T is not a named type.

This would work:

var val2 UnknownMapString  = val.(map[string]interface{})
val2.Foo()

val2 is not an unnamed type, and both val2 and val.(map[string]interface{}) underlying types are identical.

<kbd>play.golang.org</kbd>

Output:

test!

huangapple
  • 本文由 发表于 2014年8月2日 12:55:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/25091806.html
匿名

发表评论

匿名网友

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

确定