👌

Goの無名構造体の使い方

2025/02/22に公開

はじめに

Go言語では、通常typeを使って、構造体(struct)を定義しますが、テストコードなど一時的なデータを扱う場合に便利な無名構造体(anonymous struct) という機能があります。
本記事では、無名構造体の使い方を説明します。


通常の構造体

無名構造体の説明をする前に、通常の構造体について説明します。
通常の構造体は、以下のようにtypeを使って型を定義し、その後インスタンスを作成して使用します。

package main

import "fmt"

// 通常の構造体の定義
type Device struct {
    Model string
    Year  int
}

func main() {
    device := Device{Model: "X100", Year: 2023}
    fmt.Println("Model:", device.Model)
    fmt.Println("Year:", device.Year)
}

しかしながら、テストデータの記述など、一時的なデータを扱う場合型を定義するほどではない場合 では、次に説明する、無名構造体を使うことでソースコードを簡潔にできます。


無名構造体の使い方

無名構造体は struct{}を直接変数に代入して使用します。

package main

import "fmt"

func main() {
    device := struct {
        model string
        year  int
    }{
        model: "X100",
        year:  2023,
    }

    fmt.Println("Model:", device.model)
    fmt.Println("Year:", device.year)
}

また、以下のように構造体のスライスとして使用することも可能です。

package main

import "fmt"

func main() {
	// 無名構造体のスライス
	devices := []struct {
		model string
		year  int
	}{
		{model: "X100", year: 2023},
		{model: "X200", year: 2024},
		{model: "X300", year: 2025},
	}

	// スライスの要素をループで処理
	for _, device := range devices {
		fmt.Println("Model:", device.model, "Year:", device.year)
	}
}

Discussion