dougaicha5258 2015-02-20 17:20
浏览 57
已采纳

当golang是本机类型时,为什么golang禁止分配给相同的基础类型?

Consider this code:

package main
import "fmt"

type specialString string

func printString(s string) {
    fmt.Println(s)
}

// unlike, say, C++, this is not legal GO, because it redeclares printString
//func printString(s specialString) {    
//  fmt.Println("Special: " + s)
//}

func main() {
    ss := specialString("cheese")
    // ... so then why shouldn't this be allowed?
    printString(ss)
}

My question is: why is the language defined so that the call to printString(ss) in main() is not allowed? (I'm not looking for answers that point to the Golang rules on assignment; I have already read them, and I see that both specialString and string have the same 'underlying type' and both types are 'named' -- if you consider the generic type 'string' to be named, which Golang apparently does -- and so they are not assignable under the rules.)

But why are the rules like that? What problem is solved by treating the built-in types as 'named' types, and preventing you from passing named types to all the standard library functions that accepting the same underlying built-in type? Does anybody know what the language designers had in mind here?

From my point of view, it seems to create a lot of pointless type conversion in the code, and discourages the use of strong typing where it actually would make sense..

  • 写回答

2条回答 默认 最新

  • donglizuo8892 2015-02-21 11:38
    关注

    I believe the initial authors' logic here is that named type is named for a reason - it represents something different, not just underlying type.

    I guess I've read it somewhere in golang-nuts, but can't remember exact discussion.

    Consider the following example:

    type Email string
    

    You named it Email, because you need to represent e-mail entity, and 'string' is just simplified representation of it, sufficient for the very start. But later, you may want to change Email to something more complex, like:

    type Email struct {
        Address string
        Name    string
        Surname string
    }
    

    And that will break all your code that work with Email implicitly assuming it's a string.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度