LoginSignup
12
6

More than 5 years have passed since last update.

Goの値型と参照型

Posted at

Goの値型と参照型。
Array,Structは値型。
Slice,Mapは参照型。

Source

package main

import "fmt"

type Strct struct {
    a, b int
}

func aryFunc(aryVar [3]int) {
    aryVar[0] = 9
}

func sliceFunc(sliceVar []int) {
    sliceVar[0] = 9
}

func mapFunc(mapVar map[string]int) {
    mapVar["a"] = 9
}

func strctFunc(strctVar Strct) {
    strctVar.a = 9
}

func main() {
    fmt.Print("Array:\t値型\t")
    aryVar := [3]int{0, 1, 2}
    aryFunc(aryVar)
    fmt.Println(aryVar) // [0 1 2]

    fmt.Print("Slice:\t参照型\t")
    sliceVar := []int{0, 1, 2}
    sliceFunc(sliceVar)
    fmt.Println(sliceVar) // [9 1 2]

    fmt.Print("Map:\t参照型\t")
    mapVar := map[string]int{"a": 0, "b": 1, "c": 2}
    mapFunc(mapVar)
    fmt.Println(mapVar) // map[a:9 b:1 c:2]

    fmt.Print("Struct:\t値型\t")
    strctVar := Strct{a: 0, b: 1}
    strctFunc(strctVar)
    fmt.Println(strctVar) // {0 1}
}

Output

Array:  値型    [0 1 2]
Slice:  参照型  [9 1 2]
Map:    参照型  map[a:9 b:1 c:2]
Struct: 値型    {0 1}
12
6
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
12
6