1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Go】スライスのサンプルメモ

Last updated at Posted at 2020-02-13

package main

import (
"fmt"
"reflect"
)

func main() {
// 配列
arr := [3]string{"a", "b", "c"}

// スライス型の変数を宣言
var s1 []string
// スライス
s1 = arr[:]
	fmt.Println(s1) // [a b c]

	fmt.Println(reflect.TypeOf(s1)) // []string

// var を使わないVersion
s2 := arr[:]
fmt.Println(s2) // [a b c]

// インデックスを指定
s3 := arr[1:2]
fmt.Println(s3) // [b c]

s4 := arr[1:3]
fmt.Println(s4) // [b c]

// append
s5 := append(s4, "d", "e")
fmt.Println(s4) // [b c]
fmt.Println(s5) // [b c d e]

// 配列とスライスを同時に宣言
s6 := []string{"A", "B", "C"}
fmt.Println(s6)

// 長さ、キャパシティ
fmt.Println(len(s6)) // 3
fmt.Println(cap(s6)) // 3

s7 := append(s6, "D")
fmt.Println(len(s7)) // 4
fmt.Println(cap(s7)) // 6 --> 倍になった

a8 := [...]int{0, 1, 2, 3, 4}
s8 := a8[1:4]
fmt.Println(s8) // [1 2 3]
fmt.Println(len(s8)) // 3
fmt.Println(cap(s8)) // 4

s9 := a8[1:2]
fmt.Println(len(s9)) // 1
fmt.Println(cap(s9)) // 4

s10 := a8[0:5]
fmt.Println(len(s10)) // 5
fmt.Println(cap(s10)) // 5

}

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?