1 回答
TA贡献1906条经验 获得超10个赞
PersonA
您可以通过在和中嵌入一个通用结构来做这样的事情PersonB
。
例如(游乐场链接):
package main
import "fmt"
type commonPerson struct {
A string
B string
C string
}
type PersonA struct {
commonPerson
}
func (p PersonA) String() string {
return fmt.Sprintf("A: %s, %s, %s", p.A, p.B, p.C)
}
// This function is just here so that PersonA implements personInterface
func (p PersonA) personMarker() {}
type PersonB struct {
commonPerson
}
func (p PersonB) String() string {
return fmt.Sprintf("B: %s, %s, %s", p.A, p.B, p.C)
}
// This function is just here so that PersonB implements personInterface
func (p PersonB) personMarker() {}
type personInterface interface {
personMarker()
}
var smartPerson personInterface
func smartAction(personType string) {
common := commonPerson{
A: "foo",
B: "bar",
C: "Hello World",
}
switch personType {
case "A":
smartPerson = PersonA{commonPerson: common}
case "B":
smartPerson = PersonB{commonPerson: common}
}
}
func main() {
smartAction("A")
fmt.Println(smartPerson)
smartAction("B")
fmt.Println(smartPerson)
}
输出:
A: foo, bar, Hello World
B: foo, bar, Hello World
- 1 回答
- 0 关注
- 111 浏览
添加回答
举报