Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@kure

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

More than 1 year has passed since last update.

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

}

0
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
kure

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
0
Help us understand the problem. What is going on with this article?