dqoqnmb163241 2013-09-06 14:22
浏览 61
已采纳

如果我有一个定义为字符串常量的类型,为什么不能将该类型传递给实际的字符串呢?

Here's what I mean: Go playground

The "StringType" type is a string and nothing more. The compiler complains about line 21, but for some reason, line 16 works without issue (if you comment 21 and uncomment 22).

What is the difference between those two lines (as both as passing StringType to the same function), and why does one work and the other not?

Here's the code, in-line:

package main

import (
    "fmt"
    "strings"
)

type StringType string

const (
    FirstString  = "first"
    SecondString = "second"
)

func main() {
    fmt.Println(strings.Contains(FirstString, SecondString))    // line 16
}

func myFunc(a StringType, b StringType) bool {

    return strings.Contains(a, b)                               // line 21
    //return false
}
  • 写回答

3条回答 默认 最新

  • dongre9937 2013-09-06 14:29
    关注

    Go has a strict typing system. StringType and string is not the same type, and you need to do a type conversion.

    The Go specs states that:

    A non-constant value x can be converted to type T in any of these cases:

    x is assignable to T.
    x's type and T have identical underlying types.
    ...
    x is an untyped constant representable by a value of type T

    Since StringType has the underlying type of string, this conversion is possible:

    func myFunc(a StringType, b StringType) bool {
    
        return strings.Contains(string(a), string(b))
        //return false
    }
    

    Also, because FirstString and SecondString are untyped constants representable by StringType, this will allow you to pass it as a StringType, as stated by the specs.

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

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献