LoginSignup
3
3

More than 5 years have passed since last update.

Go by Example: Slices

Posted at

(この記事は Go by Example: Slices を翻訳したものです。)

SlicesはGoの中で重要なデータ構造です。arraysよりも連続したデータに対して強力なインターフェイスを提供します。

package main

import "fmt"

func main() {

    // arraysとは違い、slicesは中に入っている要素の型のみで定義されます。(要素の数は含まれない)
    // 長さがゼロではないからのsliceを作るには、buildinのmakeを使用する。
    // これは、長さが3のstringのsliceを作る例です。(値はzero valueで初期化されている。)
    s := make([]string, 3)
    fmt.Println("emp:", s)

    // arraysのように値を代入、取得することができます。
    s[0] = "a"
    s[1] = "b"
    s[2] = "c"
    fmt.Println("set:", s)
    fmt.Println("get:", s[2])

    // buildinのlenはslicesの長さを返します。
    fmt.Println("len:", len(s))

    // これらの基本的な動作以外に、sliceは複数のarraysよりも使いやすい機能をサポートしています。
    // ひとつは、新しい値を一つもしくは複数含んだsliceを返すbuildinのappendです。
    // 新しいsliceを得るためにappendからの戻り値を受けるとる必要があります。
    s = append(s, "d")
    s = append(s, "e", "f")
    fmt.Println("apd:", s)

    // sliceはコピーすることもできます。
    // ここでは、sと同じ長さのからのsliceのcを作りsからcにコピーします。
    c := make([]string, len(s))
    copy(c, s)
    fmt.Println("cpy:", c)

    // Slicesはsliceをslice[low:high]の文法でサポートしています。
    // たとえば、これは、sliceの要素のs[2],s[3],s[4]を取得します。
    l := s[2:5]
    fmt.Println("sl1:", l)

    // これはs[5]まで切り出します。(s[5]は含まれない。)
    l = s[:5]
    fmt.Println("sl2:", l)

    // これはs[2]から切り出します。(s[2:]は含まれる)
    l = s[2:]
    fmt.Println("sl3:", l)

    // ワンラインでsliceのために値を初期化し宣言することができます.
    t := []string{"g", "h", "i"}
    fmt.Println("dcl:", t)

    // Sliceは多次元構造を含むことができます。
    // 多次元のarraysとは違い、sliceの中の要素の長さは可変です。
    twoD := make([][]int, 3)
    for i := 0; i < 3; i++ {
        innerLen := i + 1
        twoD[i] = make([]int, innerLen)
        for j := 0; j < innerLen; j++ {
            twoD[i][j] = i + j
        }
    }
    fmt.Println("2d: ", twoD)
}


$ go run slices.go
emp: [  ]
set: [a b c]
get: c
len: 3
apd: [a b c d e f]
cpy: [a b c d e f]
sl1: [c d e]
sl2: [a b c d e]
sl3: [c d e f]
dcl: [g h i]
2d:  [[0] [1 2] [2 3 4]]

3
3
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
3
3