英文:
How do you typecast a map in Go into a custom type?
问题
我有一个自定义类型定义:
type Thingy map[string]interface{}
我有一个函数,它接受一个空接口参数:
func f(arg interface{})
我想做的是将arg强制转换为Thingy类型的变量。我一定是对Go的某些基本概念有误解,因为我无法使其工作:
t, ok := arg.(Thingy)
在这里,ok
总是返回false。有什么想法吗?完整的示例在这里:http://play.golang.org/p/TRZsX4v8-S
英文:
I have a custom type defined:
type Thingy map[string]interface{}
and I have a function that is passed an empty interface argument:
func f(arg interface{})
What I'd like to do is be able to typecast arg into a variable of type Thingy. I must be misunderstanding something fundamental about Go because I can't get this to work:
t, ok := arg.(Thingy)
ok
always returns false there. Any ideas? Full example here: http://play.golang.org/p/TRZsX4v8-S
答案1
得分: 3
- 这不是一个类型转换,而是一个类型断言。
- 你传递的不是一个
Thingy
,而是一个map[string]interface{}
。
重要的是要理解,尽管类型看起来相似,但并不意味着你可以互换使用它们。当存在方法集时,这一点尤为重要。即使底层类型相同,对两种不同类型的 x()
的调用也必须是可区分的。
英文:
- That's not a cast, but a type assertion.
- You're not passing a
Thingy
, but amap[string]interface{}
It's important to understand that just because types look similar, that doesn't mean you can use them interchangeably. This is most important when there are method sets. A call to x()
on two different types have to be distinguishable even if the underlying types are the same.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论