LoginSignup
0
0

More than 1 year has passed since last update.

[Go] Structs

Last updated at Posted at 2022-01-31

Structs とは

Go には関連する情報をまとめするため、 structs が使われる

Defining and Declaring

package main

import "fmt"

type person struct {
    firstName string
    lastName  string
}

func main() {
    var aaa person
    fmt.Println(aaa) // The default value is a empty string.
    fmt.Printf("%+v\n", aaa) // Use the "%+v" can print the fields also.

    // Updating Struct Values
    aaa.firstName = "aaa"
    aaa.lastName = "player"
}

Embedding Structs

Structsstructs も宣言できる

package main

import "fmt"

type contactInfo struct {
    email   string
    zipCode int
}

type person struct {
    firstName string
    lastName  string
    contact   contactInfo
}

func main() {
    aaa := person{
        firstName: "aaa",
        lastName:  "player",
        contact: contactInfo{
            email:   "aaa@mail.com",
            zipCode: 1234567,
        },
    }
    fmt.Println(aaa)
}

宣言するときに、 contactInfo だけを宣言すると

contactInfo contactInfo の書き方と同じになる

type contactInfo struct {
    email   string
    zipCode int
}

type person struct {
    firstName string
    lastName  string
    contactInfo
}

Updating Struct Values

package main

import "fmt"

type player struct {
    name  string
    score int
}

func main() {
    a := player{"aaa", 0}
    fmt.Println(a)
    a.updateScore(1)
    fmt.Println(a)
}

func (p player) updateScore(s int) {
    p.score = s
}
output
{aaa 0}
{aaa 0}

上記のupdateScore functionを使ってもaのスコアが更新できない

Pass By Value

GoPass By Valueなので、下記のように

address value note
0001 {aaa 0} 元のa値 更新されなかった
0002
0003 {aaa 0} コピーされた値 funcがこの値を更新した

元のaのスコアが更新されなかった

Pointer

address value
0001 {aaa 0}

Turn address into value with *address

Turn value into address with &value

Point Receiver

ReceiverのTypeに*を追加することで

(p *player)

宣言するtypeはstruct playerではなく、struct playerのaddressになる

そうすれば、struct aのaddressのvalueをpassでき

元のaの値を更新できるようになる

package main

import "fmt"

type player struct {
    name  string
    score int
}

func main() {
    a := player{"aaa", 0}
    fmt.Println(a)

    pointerA := &a // Turn value into address
    pointerA.updateScore(1)
    fmt.Println(a)
}

func (p *player) updateScore(s int) {
    // Turn value into address
    (*p).score = s
}
output
{aaa 0}
{aaa 1}

ちなみに、

aのvalueをadressに転換しなくても、Goも処理してくれる

package main

import "fmt"

type player struct {
    name  string
    score int
}

func main() {
    a := player{"aaa", 0}
    fmt.Println(a)

    a.updateScore(1) // Use a, the player struct type
    fmt.Println(a)
}

func (p *player) updateScore(s int) {
    (*p).score = s
}

結果も同じ

output
{aaa 0}
{aaa 1}
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