How do you typecast a map in Go into a custom type?

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

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

  1. 这不是一个类型转换,而是一个类型断言。
  2. 你传递的不是一个 Thingy,而是一个 map[string]interface{}

重要的是要理解,尽管类型看起来相似,但并不意味着你可以互换使用它们。当存在方法集时,这一点尤为重要。即使底层类型相同,对两种不同类型的 x() 的调用也必须是可区分的。

英文:
  1. That's not a cast, but a type assertion.
  2. You're not passing a Thingy, but a map[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.

huangapple
  • 本文由 发表于 2014年1月21日 15:20:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/21251660.html
匿名

发表评论

匿名网友

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

确定