[英]How to convert to typeof(field)?
Given something like this: 给定这样的东西:
type Foo struct {
x int
}
type FooFoo struct {
foo *Foo
}
type Bar struct {
x int
}
Where Foo
is hidden (in my case due to vendoring), how can I create a FooFoo struct with a valid foo entry? 在
Foo
隐藏的情况下(在我的情况下是由于供应商),如何创建具有有效foo条目的FooFoo结构?
If Foo
were available, I could do 如果有
Foo
,我可以
foofoo := &FooFoo{ foo: &Foo{5} }
or even 甚至
foofoo := &FooFoo{ foo: (*Foo)&Bar{ 5 } }
But I can't find a way to do it without mentioning Foo
. 但是我找不到不提
Foo
。
I think I would need something like: 我想我需要这样的东西:
foofoo := &FooFoo{ foo: (*typeof(FooFoo.foo)) &Bar{ 5 } }
You shouldn't set the private method from another library as per this answer . 您不应按照此答案从另一个库设置private方法。 However, the library should have an appropriate constructor.
但是,该库应具有适当的构造函数。 The library should have a method that looks like
该库应该有一个看起来像
func FooFooGenerator(appropriateInfo int) FooFoo {
... Library does the work
}
You just need to export a "constructor" function for FooFoo
and keep your foo
unexported. 您只需要为
FooFoo
导出“构造函数”功能, FooFoo
foo
导出即可。
func NewFooFoo() *FooFoo {
f := &foo{ /* initialize foo */ }
return &FooFoo{foo:f}
}
Then clients of you package will have access to NewFooFoo
, and FooFoo
, but not foo
. 然后,您的软件包的客户端将可以访问
NewFooFoo
和FooFoo
,但不能访问foo
。
And as for casting Foo
to Bar
, not sure why you would want that, but you can do it, if you are on Go1.8+ , this way (*Foo)(&Bar{ 5 })
playground . 至于将
Foo
投射到Bar
,不知道为什么会这么做,但是如果您使用的是Go1.8 + ,则可以这样做(*Foo)(&Bar{ 5 })
游乐场 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.