Upgrade to Pro — share decks privately, control downloads, hide ads and more …

go1.22で変更されたslices.Delete()の挙動について

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.

 go1.22で変更されたslices.Delete()の挙動について

Avatar for Douglas Shuhei Takeuchi

Douglas Shuhei Takeuchi

October 20, 2025
Tweet

Transcript

  1. 自己紹介 名前 : 武内修平 X(Twitter) : @ShuheiTakeuchi 所属 : OLTA株式会社

     法人カードチームでGo言語を使ったバックエ ンド開発を担当 浅草とのつながり :  学生時代に花屋敷で1年間アルバイト 写真 初LT!緊張 してます!
  2. slices.Delete()とは? package main import ( "fmt" "slices" ) func main()

    { letters := []string{"a", "b", "c", "d", "e"} letters = slices.Delete(letters, 1, 4) fmt.Println(letters) } // 出力結果 // [a e] 第2引数と第3引数で指定したイ ンデックス間の要素を第 1引数の Sliceから削除
  3. func main() { before := []string{"a", "b", "c", "d", "e"}

    after := slices.Delete(before, 1, 4) fmt.Println(before) fmt.Println(after) } slices.Delete()とは? 引数として渡したSliceの値は何 が入っているのか?
  4. func main() { before := []string{"a", "b", "c", "d", "e"}

    after := slices.Delete(before, 1, 4) fmt.Println(before) fmt.Println(after) } // 出力結果 // Go1.21 -> [a e c d e] // Go1.21 -> [a e] // Go1.22 -> [a e ] // Go1.22 -> [a e] slices.Delete()とは? • Go1.21, Go1.22共に戻り値afterの 値は同じ • beforeの値が違う ◦ Go1.21では、”b”, “c”, “d”を削除 した後に、元々index2 ~ index4 の場所にいた”c”, “d”, “e”が復 活したかのような挙動になって いる ◦ Go1.22では、”b”, “c”, “d”が削 除された後に、index2 ~ index4 の場所にはゼロ値が入っている 後ろにゼロ値が3つ 入っている
  5. Go1.21での実装 func Delete[S ~[]E, E any](s S, i, j int)

    S { _ = s[i:j] // bounds check return append(s[:i], s[j:]...) }
  6. Go1.22での実装 func Delete[S ~[]E, E any](s S, i, j int)

    S { _ = s[i:j:len(s)] // bounds check if i == j { return s } oldlen := len(s) s = append(s[:i], s[j:]...) clear(s[len(s):oldlen]) // zero/nil out the obsolete elements, for GC return s } j > len(s)かどうかの判 定が増えた 削除する要素が無い 場合はEarly Return 不要になった要素 をゼロ値化