duanke1286 2018-04-08 08:59
浏览 118
已采纳

使用字符串定义的类型值作为字符串

I have a defined named type

type User string

and now I want to use a User value as an actual string like so

func SayHello(u User) string {
    return "Hello " + user + "!"
}

But I receive an error:

cannot use "Hello " + user + "!" (type User) as type string in return argument

How do I use a named type as its underlying type?

  • 写回答

4条回答 默认 最新

  • duancao1951 2018-04-08 09:16
    关注

    From Golang Spec

    A value x is assignable to a variable of type T ("x is assignable to T") if:

    • x's type is identical to T.
    • x's type V and T have identical underlying types and at least one of V or T is not a defined type.

    Variables of named type type User string and unnamed type var user string are absolutely different. We can check that using reflection for showing the underlying type.

    package main
    
    import (
        "fmt"
        "reflect"
        )
    
    type User string
    
    func main() {
        var name User = "User"
        var name2 string = "User"
        //fmt.Print(name==name2) // mismatched types User and string
        fmt.Println(reflect.TypeOf(name2))
        fmt.Println(reflect.TypeOf(name))
    }
    

    So check the underlying type of a variable and then type cast the type to primitive one to compare the value.

    package main
    
    import (
        "fmt"
    )
    
    type User string
    
    func main() {
        var u User
        fmt.Print(SayHello(u))
    }
    
    func SayHello(u User) string {
        change := string(u)
        return "Hello " + change + "!"
    }
    

    Check on Go Playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?