dou44364983 2013-10-31 20:05
浏览 26
已采纳

如何将[]字符串转换为[]命名字符串

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条回答 默认 最新

  • drxyaox153896 2013-10-31 21:20
    关注

    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
    ", 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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示