2

私は名前付きの型を持っています

type identifier string

を返す標準ライブラリ メソッドを使用しており[]string、それを に変換したいと考えています[]identifier。それ以外にそれを行うためのよりスムーズな方法はありますか:

...
stdLibStrings := re.FindAllString(myRe, -1)
identifiers := make([]identifier, len(stdLibStrings))
for i, s := range stdLibStrings {
    identifiers[i] = identifier(s)
}

私の最終的な目標は、この名前付きidentifierの型にいくつかのメソッドを持たせることです。私が間違っていなければ、許可されていないレシーバーとして名前のない型を使用するのではなく、名前付きの型を必要とします。

ありがとう。

4

1 に答える 1

3

Go プログラミング言語仕様

割り当て可能性

[この場合]では、値 x は型 T の変数に代入可能です (「x は T に代入可能」):

x の型 V と T は同一の基になる型を持ち、V または T の少なくとも 1 つは名前付き型ではありません。

例えば、

package main

import "fmt"

type Indentifier string

func (i Indentifier) Translate() string {
    return "Translate " + string(i)
}

type Identifiers []string

func main() {
    stdLibStrings := []string{"s0", "s1"}
    fmt.Printf("%v %T\n", stdLibStrings, stdLibStrings)
    identifiers := Identifiers(stdLibStrings)
    fmt.Printf("%v %T\n", identifiers, identifiers)
    for _, i := range identifiers {
        t := Indentifier(i).Translate()
        fmt.Println(t)
    }
}

出力:

[s0 s1] []string
[s0 s1] main.Identifiers
Translate s0
Translate s1
于 2013-10-31T21:20:31.237 に答える