我可以通过某种反射摆脱开关吗?brand将始终匹配结构名称
package main
import "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()
}
慕村225694
相关分类