0
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 5 years have passed since last update.

スライスのまとめ

Posted at

個人的な備忘としてのメモです。

スライスは参照型
可変長配列であるが、ちょっと注意が必要。

sample.go
package main
import "fmt"
func main(){
    a := [5]int{1,2,3,4,5} // 配列
    s := a[0:2] // スライス
    fmt.Println("a:", a) // a: [1 2 3 4 5]
    fmt.Println("s:", s) // s: [1 2]
    
    a[0] = 10
    fmt.Println("a:", a) // a: [10 2 3 4 5]
    // 参照型なので配列の変更が影響される
    fmt.Println("s:", s) // s: [10 2]
    
    s[0] = 100
    fmt.Println("a:", a) // a: [100 2 3 4 5]
    fmt.Println("s:", s) // s: [100 2]
    
    s = append(s, 6)
    fmt.Println("a:", a) // a: [100 2 6 4 5]
    fmt.Println("s:", s) // s: [100 2 6]
    
    
    b := [3]int{1,2,3} // 配列
    t := b[:] // スライス
    fmt.Println("b:", b) // b: [1 2 3]
    fmt.Println("t:", t) // t: [1 2 3]
    
    t = append(t, 6) // スライスが自動拡張される → 参照先の配列が変わる
    fmt.Println("b:", b) // b: [1 2 3]
    fmt.Println("t:", t) // t: [1 2 3 6]
    
    b[0] = 10
    fmt.Println("b:", b) // b: [10 2 3]
    // 参照先の配列が変わったので、配列の変更が影響されない
    fmt.Println("t:", t) // t: [1 2 3 6]
}
0
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
0
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?