gpt4 book ai didi

types - 如何将 []string 转换为 []namedstring

转载 作者:IT王子 更新时间:2023-10-29 01:40:10 24 4
gpt4 key购买 nike

在 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

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.

例如,

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com