两句话,对于任何人来说,对于一个好的架构,我们应该使用接口,这些接口描述它的行为,这并不是一个秘密。Golang实现了这个想法,但他们的接口只有方法,但没有字段。因此,使用它们的唯一方法是创建获取器和设置器。但是有了这个,我在指针方面遇到了问题。
例如:
package main
import "fmt"
// A
type IA interface {
Foo() string
}
type A struct {
foo string
}
func (a *A) Foo() string {
return a.foo
}
// B
type IB interface {
A() *IA
}
type B struct {
a *IA
}
func (b *B) A() *IA {
return b.a
}
// main
func main() {
a := &A{"lol"}
b := &B{a} // cannot use a (type *A) as type *IA in field value: *IA is pointer to interface, not interface
foo := b.A().Foo() // b.A().Foo undefined (type *IA is pointer to interface, not interface)
fmt.Println(foo)
}
Ofc,我可以使用这样的东西:
(*(*b).A()).Foo()
但这会那么好和合适吗?
我只想有像蟒蛇,js,ts这样的行为:
someObj.child1.child2.child2SomeMethod()
也许我搞砸了指针,我只想知道使用嵌套对象的golang方法。
潇潇雨雨
相关分类