【发布时间】:2018-03-22 12:44:17
【问题描述】:
有人能帮我理解为什么它不能使用像 [Error 1] 和 [Error 2] 这样的语法吗?为什么 [ok 1] 是可能的并且工作得很好。
使用 Animal 作为字段作为泛型类型的基本设计好吗?或者有什么不好的地方吗?或者有什么更好的解决方案?
package main
import (
pp "github.com/davecgh/go-spew/spew"
)
type Cat struct {
Name string
Age int
}
type Animal interface{}
type House struct {
Name string
Pet *Animal
}
func config() *Animal {
c := Cat{"miao miao", 12}
// return &Animal(c) //fail to take address directly [Error 1]
// return &(Animal(c)) //fail to take address directly [Error 2]
a := Animal(c) //[Ok 1]
return &a
}
func main() {
pp.Dump(config())
pp.Dump(*config())
pp.Dump((*config()).(Cat)) //<-------- we want this
pp.Dump((*config()).(Cat).Name)
pp.Dump("---------------")
cfg := config()
pp.Dump(&cfg)
pp.Dump(*cfg)
pp.Dump((*cfg).(Cat)) //<-------- we want this
pp.Dump((*cfg).(Cat).Name)
pp.Dump("---------------")
}
【问题讨论】:
标签: pointers go syntax interface