Go/ユーザー定義型の配列とスライス
表示
< Go
Go言語では、ユーザー定義型の配列とスライスを作成することができます。それぞれの特徴と使い方を説明します。
ユーザー定義型の配列
[編集]基本的な定義
[編集]type Person struct { Name string Age int } // 固定長の配列 var people [3]Person // 初期化 people = [3]Person{ {"田中", 30}, {"佐藤", 25}, {"鈴木", 35}, } // またはリテラルで直接初期化 people2 := [3]Person{ {Name: "山田", Age: 28}, {Name: "中村", Age: 32}, {Name: "高橋", Age: 29}, }
配列の特徴
[編集]// 長さは固定 fmt.Println(len(people)) // 3 // インデックスでアクセス fmt.Println(people[0].Name) // "田中" // 値型なので代入時にコピーが作成される people3 := people2 // 完全なコピー people3[0].Name = "変更" fmt.Println(people2[0].Name) // "山田"(元の値は変更されない)
ユーザー定義型のスライス
[編集]基本的な定義
[編集]// 動的な長さのスライス var people []Person // make関数で初期化 people = make([]Person, 0, 10) // 長さ0、容量10 // リテラルで初期化 people = []Person{ {"田中", 30}, {"佐藤", 25}, {"鈴木", 35}, }
スライスの基本操作
[編集]// 要素の追加 people = append(people, Person{"新田", 27}) // 複数要素の追加 people = append(people, Person{"森田", 33}, Person{"小林", 26}) // 別のスライスを展開して追加 morePeople := []Person{{"吉田", 31}, {"井上", 24}} people = append(people, morePeople...) // 長さと容量 fmt.Println(len(people)) // 現在の要素数 fmt.Println(cap(people)) // 容量
スライスの操作例
[編集]// 範囲指定でのアクセス first3 := people[0:3] // 最初の3要素 last2 := people[len(people)-2:] // 最後の2要素 // 要素の削除(インデックス1を削除) people = append(people[:1], people[2:]...) // 要素の挿入(インデックス1に挿入) newPerson := Person{"挿入", 40} people = append(people[:1], append([]Person{newPerson}, people[1:]...)...)
実践的な使用例
[編集]type Student struct { ID int Name string Grade int } // 学生管理システム type ClassRoom struct { Students []Student Name string } func (c *ClassRoom) AddStudent(student Student) { c.Students = append(c.Students, student) } func (c *ClassRoom) GetAverageGrade() float64 { if len(c.Students) == 0 { return 0 } total := 0 for _, student := range c.Students { total += student.Grade } return float64(total) / float64(len(c.Students)) } // 使用例 classroom := ClassRoom{ Name: "3年A組", Students: make([]Student, 0), } classroom.AddStudent(Student{1, "太郎", 85}) classroom.AddStudent(Student{2, "花子", 92}) classroom.AddStudent(Student{3, "次郎", 78}) fmt.Printf("平均点: %.2f\n", classroom.GetAverageGrade())
重要なポイント
[編集]配列の特徴
[編集]- 固定長: 宣言時にサイズが決まり、変更できません
- 値型: 代入時に全体がコピーされます
- メモリ効率: 事前に確保されたメモリを使用します
スライスの特徴
[編集]- 動的長: 実行時に要素を追加・削除できます
- 参照型: 元の配列への参照を保持します
- 柔軟性: 長さを変更できるため、実用的です
一般的に、固定サイズが分かっている場合は配列、動的にサイズが変わる場合はスライスを使用します。実際の開発では、スライスの方がよく使われます。