英文:
How can I convert []string to []namedstring
问题
在Go语言中,我有一个命名类型:
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
的类型拥有一些方法。如果我没记错的话,这些方法需要一个命名类型作为接收器,而不能使用未命名类型。
谢谢。
英文:
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.
答案1
得分: 3
《Go编程语言规范》
可赋值性
在以下情况下,值x可以赋值给类型为T的变量("x可以赋值给T"):
x的类型V和T具有相同的基础类型,并且V或T中至少有一个不是命名类型。
例如,
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
英文:
> The Go Programming Language Specification
>
> Assignability
>
> 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\n", stdLibStrings, stdLibStrings)
identifiers := Identifiers(stdLibStrings)
fmt.Printf("%v %T\n", 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论