Skip to content

Instantly share code, notes, and snippets.

@giwa
Created January 25, 2015 07:12
Show Gist options
  • Save giwa/ade9ef7a0104b9f279fe to your computer and use it in GitHub Desktop.
Save giwa/ade9ef7a0104b9f279fe to your computer and use it in GitHub Desktop.
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]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment