Go结构中的无名字段?

wljmcqd8  于 12个月前  发布在  Go
关注(0)|答案(3)|浏览(89)
package main

import "fmt"

type myType struct {
    string
}

func main() {
    obj := myType{"Hello World"}

    fmt.Println(obj)
}

结构中的无名字段有什么用途?
是否可以像访问命名字段那样访问这些字段?

xuo3flqw

xuo3flqw1#

没有不尊重选择的答案,但它没有澄清我的概念。
有两件事正在发生。首先是匿名字段。二是“提升”领域。
对于匿名字段,可以使用的字段名是类型的名称。第一个匿名字段是“提升的”,这意味着您在结构上访问的任何字段都“传递”到提升的匿名字段。这显示了两个概念:

package main

import (
    "fmt"
    "time"
)

type Widget struct {
    name string
}

type WrappedWidget struct {
    Widget       // this is the promoted field
    time.Time    // this is another anonymous field that has a runtime name of Time
    price int64  // normal field
}

func main() {
    widget := Widget{"my widget"}
    wrappedWidget := WrappedWidget{widget, time.Now(), 1234}

    fmt.Printf("Widget named %s, created at %s, has price %d\n",
        wrappedWidget.name, // name is passed on to the wrapped Widget since it's
                            // the promoted field
        wrappedWidget.Time, // We access the anonymous time.Time as Time
        wrappedWidget.price)

    fmt.Printf("Widget named %s, created at %s, has price %d\n",
        wrappedWidget.Widget.name, // We can also access the Widget directly
                                   // via Widget
        wrappedWidget.Time,
        wrappedWidget.price)
}

输出为:

Widget named my widget, created at 2009-11-10 23:00:00 +0000 UTC m=+0.000000001, has price 1234
Widget named my widget, created at 2009-11-10 23:00:00 +0000 UTC m=+0.000000001, has price 1234```
63lcw9qa

63lcw9qa2#

参见“Embedding in Go”:在结构体中嵌入匿名字段:这通常用于嵌入式结构,而不是string等基本类型。该类型没有要公开的“提升字段”。
如果x.f是表示字段或方法f的法律的选择器,则结构x中匿名字段的字段或方法f被称为promoted
提升字段的作用类似于结构的普通字段,只是它们不能用作结构的复合文本中的字段名称。
(here string本身没有字段)
请参见“Embeddding when to use pointer”中的类型嵌入示例。
是否可以像访问命名字段那样访问这些字段?
fmt.Println(obj.string)将返回Hello World而不是{Hello World}

gj3fmq9x

gj3fmq9x3#

匿名字段是没有名字的字段。您可以通过以下类型访问它:

type myType struct {
    string
}

func main() {
    obj := myType{"Hello World"}

    fmt.Println(obj.string)
}

当一个 anonymous field 是一个结构体并且有自己的字段时,这些字段被 * 提升 * 为可访问的,就好像它们是父结构体的直接字段一样(除非父结构体已经有一个具有该名称的字段):

type myType struct {
    string
    j int
}
type myParentType struct {
    myType
    i int
}

func main() {
    o := myType{"Hello World", 0}
    obj := myParentType{o, 1}

    fmt.Println(obj.j)        // 0
    fmt.Println(obj.myType.j) // 0, also works
    fmt.Println(obj.i)        // 1
}

相关问题