英文:
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
的类型V
和T
具有相同的底层类型,并且V
或T
中至少有一个不是命名类型时,x
可以赋值给类型T
("x
可以赋值给T
")。
这将起作用:
var val2 UnknownMapString = val.(map[string]interface{})
val2.Foo()
val2
不是未命名类型,而且 val2
和 val.(map[string]interface{})
的底层类型是相同的。
输出:
test!
英文:
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论