Question: Converting interface to struct

blov · 2015-09-08 20:55:39 · 2320 次点击    
这是一个分享于 2015-09-08 20:55:39 的资源,其中的信息可能已经有所发展或是发生改变。

The following code doesn't convert: http://play.golang.org/p/8kWAndjG9Z

My main objective is to make a lots of structs with similar definitions to use a specific function using the power of interfaces. MyTestStruct.Data can be typed anything including int, string, []string, struct etc.


评论:

rco8786:

It looks like you're trying to fake generics.

In general though, you're trying to cast an anonymous struct with the signature Id int, Data interface to a named struct with the signature Id int, Data []string. I'm not sure why you'd expect that to work.

QThellimist:

This works http://play.golang.org/p/HtD2OKViJ6
This doesn't work http://play.golang.org/p/JZAQjEb8il (I changed the type from []string to interface{})

Conversion between struct to struct doesn't work including casting to interface{}. Maybe there is a work around.

rco8786:

Because you're casting from interface{} to interface{}.

barsonme:

It works because they're all pointers to type T

In your other example you have two fundamentally different types:

type foo struct { A int; B []string }
bar := foo{
    A: 21,
    B: []string{"Hello, world!"},
}

and

baz := struct {
    A int
    B interface{}
} {
    A: 21,
    B: []string{"Hello, world!"},
}
QThellimist:

True. Is there a work around you can think of?

jerf:

No. Go is neither covariant nor contravariant. Types are either equal or they aren't.

You have to either take the structs apart and deal with the pieces, or use reflection. Type assertions are only "assertions", not "coercions" of any kind.


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2320 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传