How can I convert []string to []namedstring

huangapple go评论147阅读模式
英文:

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

huangapple
  • 本文由 发表于 2013年11月1日 04:05:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/19715646.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定