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?
If Foo
were available, I could do
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
.
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. 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.
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
.
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.