简体   繁体   English

如何转换为typeof(field)?

[英]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 . 然后,您的软件包的客户端将可以访问NewFooFooFooFoo ,但不能访问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.

相关问题 在Go中,如何使用匿名字段方法获取TypeOf类型? - In Go, how can I get the TypeOf a type using an anonymous field method? 如何使用reflect.TypeOf([] string {“ a”})。Elem()? - how to use reflect.TypeOf([]string{“a”}).Elem()? 如何使用MarshalJSON将结构转换为具有自定义字段类型的公共结构 - How to convert a structure to a public structure with custom field types with MarshalJSON 如何使用特定字段作为键将结构转换为 map? - how to convert a struct to a map using a specific field as key? 将结构字段转换为字符串 - Convert struct field to string 将字符串数组转换为字段名称 - Convert array of strings to field name 如何遍历reflect.TypeOf(interface {})上的* T func? - How to iterate through *T funcs from struct over reflect.TypeOf(interface{})? reflect.TypeOf 是 *string 并返回 0xc0001ae4a8 - 如何打印 - reflect.TypeOf is *string and returns 0xc0001ae4a8 - how to print 我正在尝试将以下 yaml 解组为以下结构,如何将 List 字段转换为 map 字段并使用结构访问它? - I am trying to unmarshall the following yaml into the below structs, how do I convert the List field into a map field and access it using struct? 如何将具有父字段的对象的平面列表转换为 Golang 中的嵌套树状数组结构 - How to convert a flat list of objects with parent field, into a nested tree-like array structure in Golang
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM