LoginSignup
0
0

【Go言語】構造体

Last updated at Posted at 2023-12-09

構造体とは

構造体は、異なる型のデータを一つの単位としてまとめるための複合型のこと。
構造体は非常に重要な役割を担い、データ構造を定義するのに広く用いられる。

構造体の定義

構造体の定義は、typeキーワードに続いて構造体の名前structキーワードを用いて行う。
ブレース{}内には、構造体のフィールドを列挙する。

サンプル

type Book struct {
    Title      string
    Author     string
    Publisher  string
    ReleasedAt time.Time
    ISBN       string
}

構造体のインスタンス化

構造体自体は単なる型であり、メモリ上に実体を持つインスタンスを生成する必要がある。

サンプル

package main

import (
	"fmt"
	"time"
)

type Book struct {
	Title      string
	Author     string
	Publisher  string
	ReleasedAt time.Time
	ISBN       string
}

func main() {
	var b1 Book                   // 全フィールドをゼロ値で初期化
	b2 := Book{Title: "初めてのGo言語"} // 初期値を指定
	b3 := &Book{Title: "実用 Go言語"} // ポインターとしてインスタンスを生成

	fmt.Println(b1) // {   0001-01-01 00:00:00 +0000 UTC }
	fmt.Println(b2) // {初めてのGo言語   0001-01-01 00:00:00 +0000 UTC }
	fmt.Println(b3) // &{実用 Go言語   0001-01-01 00:00:00 +0000 UTC }

}

JSONとの相互変換

JSONファイルを読み込み、それを構造体にマッピングすることができる。

サンプル

main.goと同じディレクトリにbook.jsonを用意する

{
    "title": "架空のプログラミング入門",
    "author": "山田太郎",
    "publisher": "テスト出版社",
    "release_at": "2022-04-01T00:00:00Z",
    "isbn": "123-4567890123"
}
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
	"time"
)

// Book 構造体はJSONとの相互変換を可能にするタグ付きフィールドを持つ
type Book struct {
	Title      string    `json:"title"`
	Author     string    `json:"author"`
	Publisher  string    `json:"publisher"`
	ReleasedAt time.Time `json:"release_at"`
	ISBN       string    `json:"isbn"`
}

func main() {
	f, err := os.Open("book.json")
	if err != nil {
		log.Fatal("file open error: ", err)
	}
	defer f.Close()

	d := json.NewDecoder(f)
	var b Book
	err = d.Decode(&b)
	if err != nil {
		log.Fatal("decode error: ", err)
	}

	fmt.Println(b) // {架空のプログラミング入門 山田太郎 テスト出版社 2022-04-01 00:00:00 +0000 UTC 123-4567890123}
}

参考

0
0
0

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