ダッシュで奪取

ゲーム、読書、人生

Goの構造体

基本

package main
import "fmt"

func main() {
    type pokemon struct {
        name  string
        types []string
    }
    pokemon1 := pokemon{
        "フシギダネ",
        []string{"くさ", "どく"},
    }
    fmt.Println(pokemon1) // {フシギダネ [くさ どく]}
}

フィールド数が多い場合

フィールド名を指定して書くとわかりやすい

package main
import "fmt"

func main() {
    type pokemon struct {
        name  string
        types []string
        h     int
        a     int
        b     int
        c     int
        d     int
        s     int
    }
    pokemon1 := pokemon{
        name:  "フシギダネ",
        types: []string{"くさ", "どく"},
        h:     45,
        a:     49,
        b:     49,
        c:     65,
        d:     65,
        s:     45,
    }
    fmt.Println(pokemon1) // {フシギダネ [くさ どく] 45 49 49 65 65 45}
}

値の後入れもできる

package main
import "fmt"

func main() {
    type pokemon struct {
        name  string
        types []string
    }
    pokemon1 := pokemon{}
    pokemon1.name = "フシギダネ"
    pokemon1.types = []string{"くさ", "どく"}
    fmt.Println(pokemon1) // {フシギダネ [くさ どく]}
}