我可以通过某种反射摆脱开关吗?brand将始终匹配结构名称package mainimport "fmt"type Car interface { Move() SetModel()}type Ford struct { Model string}type Volkswagen struct { Model string}func (car *Ford) Move() { fmt.Println(car.Model + " is moving!")}func (car *Ford) SetModel() { car.Model = "Focus"}func (car *Volkswagen) Move() { fmt.Println(car.Model + " is moving!")}func (car *Volkswagen) SetModel() { car.Model = "Jetta"}func main() { var car Car brand := "Ford" switch brand { case "Ford": car = &Ford{} case "Volkswagen": car = &Volkswagen{} } car.SetModel() car.Move()}
1 回答
慕村225694
TA贡献1880条经验 获得超4个赞
您不能使用reflect仅从其名称的字符串生成类型,因此可能需要类型工厂的映射,但是根据您所说的需要,您可能希望以编程方式生成它go generate。它基本上会像这样工作:
var constructors = map[string]func() Car{
"Ford": func() Car{
return &Ford{}
},
"Volkswagen": func() Car{
return &Volkswagen{}
},
}
// ...
car := constructors[brand]()
- 1 回答
- 0 关注
- 122 浏览
添加回答
举报
0/150
提交
取消