如何将变量转换为指定类型(typeof(field))?

huangapple go评论72阅读模式
英文:

How to convert to typeof(field)?

问题

给定类似以下的代码:

type Foo struct {
  x int
}

type FooFoo struct {
  foo *Foo
}

type Bar struct {
  x int
}

在我的情况下,Foo是隐藏的(可能是由于使用了供应商管理工具)。那么,如何创建一个具有有效foo字段的FooFoo结构体呢?

如果Foo是可用的,我可以这样做:

foofoo := &FooFoo{ foo: &Foo{5} }

甚至可以这样做:

foofoo := &FooFoo{ foo: (*Foo)(&Bar{5}) }

但是我找不到一种不提及Foo的方法来实现这个目标。

我认为我需要类似这样的解决方案:

foofoo := &FooFoo{ foo: (*typeof(FooFoo.foo))(&Bar{5}) }

请注意,这只是一种假设的解决方案,实际上并不能在Go语言中实现。

英文:

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 } }

答案1

得分: 1

你不应该从另一个库中设置私有方法(根据这个答案)。然而,该库应该有一个适当的构造函数。该库应该有一个类似下面的方法:

func FooFooGenerator(appropriateInfo int) FooFoo {
    // ...库执行工作
}
英文:

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 
}

答案2

得分: 0

你只需要为FooFoo导出一个"constructor"函数,并保持foo未导出。

func NewFooFoo() *FooFoo {
    f := &foo{ /* 初始化 foo */ }
    return &FooFoo{foo:f}
}

然后你的包的客户端将可以访问NewFooFooFooFoo,但不能访问foo

至于将Foo转换为Bar,不确定你为什么想要这样做,但如果你使用的是**Go1.8+**版本,你可以这样做:(*Foo)(&Bar{ 5 }) playground

英文:

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.

huangapple
  • 本文由 发表于 2017年3月21日 05:26:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/42914259.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定