In go I have a named type
type identifier string
I am using a standard library method that returns []string
and I want to convert that into []identifier
. Is there a smoother way to do that other than:
...
stdLibStrings := re.FindAllString(myRe, -1)
identifiers := make([]identifier, len(stdLibStrings))
for i, s := range stdLibStrings {
identifiers[i] = identifier(s)
}
My end goal is to have this named identifier
type have some methods which, if I'm not mistaken, require a named type versus using a unnamed type as a receiver which isn't allowed.
Thanks.
The Go Programming Language Specification
A value x is assignable to a variable of type T ("x is assignable to T") in [this case]:
x's type V and T have identical underlying types and at least one of V or T is not a named type.
For example,
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
", stdLibStrings, stdLibStrings)
identifiers := Identifiers(stdLibStrings)
fmt.Printf("%v %T
", identifiers, identifiers)
for _, i := range identifiers {
t := Indentifier(i).Translate()
fmt.Println(t)
}
}
Output:
[s0 s1] []string
[s0 s1] main.Identifiers
Translate s0
Translate s1