简体   繁体   English

在Go中为map [string] interface {}创建方法

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

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 接口转换:接口是map [string] interface {},不是main.UnknownMapString

The map[string]interface{} is unmarshaled from JSON input. map [string] interface {}从JSON输入中取消编组。

Playground replicating it -> http://play.golang.org/p/kvw4dcZVNH 复制它的游乐场-> 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. 我以为您不能将接口作为方法的接收器,因此我们需要将assert(不是转换?)键入到具名类型,并使用该具名类型作为方法的接收器。 Please let me know what I'm doing wrong. 请让我知道我在做什么错。 Thanks! 谢谢!

val = val.(UnknownMapString)

This is a type assertion , which supposes the named type UnknownMapString is identical to the unnamed type map[string]interface{} . 这是一个类型断言 ,它假定命名类型 UnknownMapString与未命名类型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 但是:您可以 map[string]interface{}分配给UnknownMapString因为

x is assignable to a variable of type T (" x is assignable to T ") when: x可以分配给类型T的变量(“ x可以分配给T ”):

x 's type V and T have identical underlying types and at least one of V or T is not a named type. x的类型VT具有相同的基础类型,并且VT中的至少一个不是命名类型。

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. val2不是未命名的类型,并且val2val.(map[string]interface{})基础类型都是相同的。

play.golang.org play.golang.org

Output: 输出:

test!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM