いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

Goメモ-209 (golang.org/x/exp/slices)(Go 1.18 リリース時には含まれなかった汎用スライス処理)

概要

忘れないうちにメモメモ。。。便利ですね。そのうち標準ライブラリに含まれるのを希望。

pkg.go.dev

サンプル

package exp_slices

import (
    "github.com/devlights/gomy/output"
    "golang.org/x/exp/slices"
)

// ExpSlices -- Go 1.18 リリース時には含まれなかったジェネリクス対応 汎用slice処理が定義されている golang.org/x/exp/slices パッケージのサンプルです。
//
// REFERENCES
//   - https://pkg.go.dev/golang.org/x/exp/slices
func ExpSlices() error {
    var (
        s1 = []string{"hello", "world"}
        s2 = []string{"hello", "world"}
        s3 = []string{"world", "hello"}
        s4 = []int{100, 101}
    )

    output.Stdoutl("[Equal(s1, s2)]", slices.Equal(s1, s2))
    output.Stdoutl("[Equal(s2, s3)]", slices.Equal(s2, s3))
    // compile error
    //fmt.Println(slices.Equal(s1, s4))

    s5 := slices.Insert(s4, 1, 999)
    output.Stdoutl("[Insert]", s4, s5)

    idx := slices.Index(s5, 999)
    s6 := slices.Delete(s5, idx, idx+1)
    output.Stdoutl("[Delete]", s5, s6)

    return nil
}

実行すると以下のような感じです。

gitpod /workspace/try-golang (master) $ task
task: [run] go run . -onetime

ENTER EXAMPLE NAME: exp_slices

[Name] "generics_exp_slices"
[Equal(s1, s2)]      true
[Equal(s2, s3)]      false
[Insert]             [100 101] [100 999 101]
[Delete]             [100 101 101] [100 101]


[Elapsed] 15.57µs

過去の記事については、以下のページからご参照下さい。

サンプルコードは、以下の場所で公開しています。