構造体とインターフェース

Go Structs

Group related values into your own type with named fields.

  • 中級
  • 約3分で読めます
  • 実行できるサンプル 1 件
学べること
  • Defining a struct
  • Fields and %+v
  • Structs are copied
User
Name"Ada"
Age37
Activetrue

Your own type with named fields

A struct is a type you define by naming its fields. It keeps related data together, such as the name, age and status of a user.

Fields are read and changed with a dot. %v prints the values and %+v adds the field names. Assigning a struct copies it, so changing guest does not change user. A struct can also be declared in place without a name.

重要なポイント

  1. Fields are read and changed with a dot.
  2. %+v prints the field names too.
  3. Assigning a struct copies it.

実行できる Go のサンプル

Go
コードを実行 →
main.go
package main

import "fmt"

type User struct {
	Name   string
	Age    int
	Active bool
}

func main() {
	user := User{Name: "Ada", Age: 36, Active: true}
	user.Age++

	fmt.Println(user.Name, user.Age)
	fmt.Printf("%v\n%+v\n", user, user)

	guest := user // structs are copied on assignment
	guest.Name = "Guest"
	fmt.Println(user.Name, guest.Name)

	point := struct{ X, Y int }{3, 4}
	fmt.Println(point.X + point.Y)
}
この例の実行ボタンを作成 実行結果
Ada 37
{Ada 37 true}
{Name:Ada Age:37 Active:true}
Ada Guest
7

練習

サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。

このレッスンを終えましたか?

学習済みにすると進み具合を記録できます。

チャレンジで練習する

このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。

すべてのチャレンジ