Can I get rid of the switch with some sort of reflection? brand
will always match the struct name
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()
}
Aucun commentaire:
Enregistrer un commentaire