Go 構造体の名前のないフィールド? 質問する

Go 構造体の名前のないフィールド? 質問する
package main

import "fmt"

type myType struct {
    string
}

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

    fmt.Println(obj)
}

構造体内の名前のないフィールドの目的は何ですか?

名前付きフィールドと同じように、これらのフィールドにアクセスすることは可能ですか?

ベストアンサー1

選ばれた回答に失礼はありませんが、私にとっては概念が明確になりませんでした。

2 つのことが起こっています。1 つ目は匿名フィールドです。2 つ目は「昇格」フィールドです。

匿名フィールドの場合、使用できるフィールド名は型の名前です。最初の匿名フィールドは「昇格」されます。つまり、構造体でアクセスするすべてのフィールドは、昇格された匿名フィールドに「渡される」ということです。これは、両方の概念を示しています。

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

おすすめ記事