Ste*_*eng 3 syntax pointers interface go
有人可以帮助我理解为什么它无法使用 [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("---------------")
}
Run Code Online (Sandbox Code Playgroud)
Mil*_*sen 10
好的,两件事:
| 归档时间: |
|
| 查看次数: |
2763 次 |
| 最近记录: |