8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Golang 無名struct の初期化

Last updated at Posted at 2019-02-16

はじめに

Go言語で、無名structを宣言と同時に初期化する構文に出会って混乱したので、備忘録のため以下に整理します。

値を指定して初期化

無名structを初期化するときに、値を指定して初期化することができます。

Playgroundのリンク
https://play.golang.org/p/7Ntgq9g_0Dj

Go言語のコード

package main

import (
	"fmt"
)

func main() {
    teststruct := struct {
    	Message string `json:"message"`
    	Number int `json:"number"`
    }{
    	"hello",
    	1,
    }

	fmt.Println(teststruct)
}

Printlnで以下が出力されます

{Hello 1}

teststruct 変数に、初期化と同時に無名structを代入しています。該当部分を下に抜粋します。
Messageフィールドには hello という文字列で初期化され、Numberフィールドには1という数値で初期化されます。

    teststruct := struct {
    	Message string `json:"message"`
    	Number int `json:"number"`
    }{
    	"hello",
    	1,
    }

関数を使用して初期化

関数や式を使用して、フィールドを初期化することもできます

Playgroundのリンク
https://play.golang.org/p/39O1hTC1H4y

Go言語のコード

package main

import (
	"fmt"
)

func main() {
    teststruct := struct {
    	Message string `json:"message"`
    	Number int `json:"number"`
    }{
    	fmt.Sprintf("Hello"),
    	1+1,
    }

	fmt.Println(teststruct)
}

Printlnで以下が出力されます

{Hello 2}

Messageには、fmt.Sprintf("Hello")の返り値が代入され、
Numberには 1+1 の結果が代入されています。

フィールドを明示的に指定

以下のように初期化するフィールドを明示的に指定して初期化することもできます

Playgroundのリンク
https://play.golang.org/p/CprTjrDdIAX

Go言語のコード

package main

import (
	"fmt"
)

func main() {
    teststruct := struct {
    	Message string `json:"message"`
    	Number int `json:"number"`
    }{
    	Message: fmt.Sprintf("Hello"),
    	Number: 1+1,
    }

	fmt.Println(teststruct)
}
8
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?