关于多个结构体如何定义变量
1. 运行环境
- Go版本:
go1.16.4
2. 问题描述?
我如果有三个结构体
type football struct {
...
}
type basketball struct {
...
}
type pingpong struct {
...
}
我想通过一个switch 根据一个变量来决定调用哪个结构体
...
//错误代码 我希望通过switch后能获取一个可用的sportStruct变量
switch sports {
case "football":
sportStruct = football{...}
case "basketball":
sportStruct = basketball{...}
case "pingpong":
sportStruct = pingpong{...}
default:
sportStruct = XXX{...}
}
...
3. 您期望得到的结果?
希望sportStruct变量可用
4. 您实际得到的结果?
尝试在switch外层定义 但不知道sportStruct 应该定义成什么类型
尝试通过:=
每个分支上都写上sportStruct变量 但还是提示未定义
强类型语言不支持这样定义吧,看楼上说的空接口可以实现,可以考虑通过
策略模式
解决