如何在 golang 里的 map 的同一个 key 放不同的 struct?

2021-03-11 19:30:01 +08:00
 yellowmarlboro
package learn

type A struct {

}

type B struct {

}

type Tasks struct {
	Name string
	ToSt Te
}

type Te interface{
	Tes()
}

func (s *A)Tes() {
}

func (s *B)Tes() {
}

func TT() {
	var1 := Tasks{Name: "s", ToSt: A{}}
}
1697 次点击
所在节点    Go 编程语言
8 条回复
rrfeng
2021-03-11 19:34:50 +08:00
首先你这也不是 map 呀

可以用 interface,不过不要用空 interface
rekulas
2021-03-11 19:37:31 +08:00
ToSt 改成 interface 不就可以么
lewinlan
2021-03-11 22:21:41 +08:00
&A{}即可。
因为 A 没有实现接口,*A 实现了。
unixeno
2021-03-11 22:23:00 +08:00
map[string]interface{}
yrj
2021-03-12 04:07:36 +08:00
三楼正解
ly020044
2021-03-12 08:17:13 +08:00
3 楼没毛病,因为你 A, B 都是用指针对象实现的接口
sherlockwhite
2021-03-12 15:20:43 +08:00
package main

type A struct {

}

type B struct {

}

type Te interface{
Tes()
}

type Tasks struct {
Name string
ToSt Te
}

func (s *A) Tes() {

}

func (s *B) Tes() {
}

func TT() {
var test A
var1 := Tasks{Name: "s", ToSt: &test}
}
sherlockwhite
2021-03-12 15:21:17 +08:00
3 楼正解

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/760802

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX