作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
在 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
类型有一些方法,如果我没记错的话,这些方法需要一个命名的类型,而不是使用一个未命名的类型作为接收者,这是不允许的。
谢谢。
最佳答案
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.
例如,
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
关于types - 如何将 []string 转换为 []namedstring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19715646/
在 go 中我有一个命名类型 type identifier string 我正在使用返回 []string 的标准库方法,我想将其转换为 []identifier。除了: ... stdLibStr
我是一名优秀的程序员,十分优秀!