golangの日記

Go言語を中心にプログラミングについてのブログ

Go言語(golang) type で定義したスライスのインデックス

golang.png


typeで実態が何らかのスライス型を定義してインデックスを使いたい。
以下ようにレシーバがポインタだと does not support indexing になる。

package main

type A []string

func (a A) Get(i int) string {
    return a[i]
}

func (a *A) Add(s string) {
    *a = append(*a, s)
}

func (a *A) Del(s string) {
    for i, v := range *a {
        if v == s {
            // does not support indexing
            *a = append(*a[:i], *a[i+1:]...)
            break
        }
    }
}



レシーバがポインタの場合は (*a)[i] とすればできる

package main

import "fmt"

type A []string

func (a A) Get(i int) string {
    return a[i]
}

func (a *A) Add(s string) {
    *a = append(*a, s)
}

func (a *A) Del(s string) {
    for i, v := range *a {
        if v == s {
            *a = append((*a)[:i], (*a)[i+1:]...)
            break
        }
    }
}

func main() {
    a := A{"foo", "bar"}
    fmt.Println(a.Get(0)) // foo
    fmt.Println(a.Get(1)) // bar

    a.Add("baz")
    fmt.Println(a) // [foo bar baz]

    a.Del("bar")
    fmt.Println(a) // [foo bar]
}