Goのドット3つ

概要

Goを書いているときに見るドット3つについて公式ドキュメントのリンクをもとにコード例を示す。

配列

https://golang.org/ref/spec#Composite_literals

The notation ... specifies an array length equal to the maximum element index plus one.

とあるように下記の例だとdaysのインデックスが[0,1]であり、最大のインデックス1に1を追加して2となる。

package main

import (
    "fmt"
)

func main() {
    days := [...]string{"Sat", "Sun"}  
    fmt.Println(len(days)) //2
    arr := [2]string{"foo", "bar"}  
    fmt.Println(len(arr))  //2
}

可変長引数

https://golang.org/ref/spec#Passing_arguments_to_..._parameters
複数の引数を渡したいときは下記のように書く。

package main

import (
    "fmt"
)

func main() {
    Greeting("nobody")                          //nobody
    Greeting("hello:", "Joe", "Anna", "Eileen") //hello:Joe Anna Eileen
    s := []string{"James", "Jasmine"}
    Greeting("goodbye:", s...) //goodbye:James Jasmine
    // Greeting("goodbye:", s) //cannot use s (type []string) as type string in argument to Greeting

}

func Greeting(prefix string, who ...string) {
    fmt.Printf("%s", prefix)
    for _, val := range who {
        fmt.Printf("%s ", val)
    }
    fmt.Println()
}

スライスの追記とコピー

https://golang.org/ref/spec#Appending_and_copying_slices

package main

import (
    "fmt"
)

func main() {
    s0 := []int{0, 0}
    s1 := append(s0, 2)              // append a single element     s1 == []int{0, 0, 2}
    s2 := append(s1, 3, 5, 7)        // append multiple elements    s2 == []int{0, 0, 2, 3, 5, 7}
    s3 := append(s2, s0...)          // append a slice              s3 == []int{0, 0, 2, 3, 5, 7, 0, 0}
    s4 := append(s3[3:6], s3[2:]...) // append overlapping slice    s4 == []int{3, 5, 7, 2, 3, 5, 7, 0, 0}
    fmt.Println(s4)

    var t []interface{}
    t = append(t, 42, 3.1415, "foo") //                             t == []interface{}{42, 3.1415, "foo"}

    var b []byte
    b = append(b, "bar"...) // append string contents      b == []byte{'b', 'a', 'r' }

}