当golang是本机类型时,为什么golang禁止分配给相同的基础类型? [英] Why does golang prohibit assignment to same underlying type when one is a native type?

查看:66
本文介绍了当golang是本机类型时,为什么golang禁止分配给相同的基础类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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)
}

我的问题是:为什么定义了语言,因此不允许在main()中调用printString(ss)? (我并不是在寻找指向Golang赋值规则的答案;我已经阅读了它们,而且我发现specialString和string都具有相同的``底层类型'',并且两种类型都被命名为-如果您考虑通用类型字符串",Golang显然是这么做的,因此根据规则它们是不可分配的.)

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..

推荐答案

我相信这里最初的作者的逻辑是,命名类型的命名是有原因的-它代表的是不同的东西,而不仅仅是基础类型.

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

我想我已经在golang-nuts的某个地方读过了,但是记不清确切的讨论了.

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

请考虑以下示例:

type Email string

您将其命名为Email,是因为您需要表示电子邮件实体,而'string'只是它的简化表示形式,从一开始就足够了.但是稍后,您可能需要将Email更改为更复杂的内容,例如:

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
}

这将破坏您所有与Email一起工作的代码,并假设它是字符串.

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

这篇关于当golang是本机类型时,为什么golang禁止分配给相同的基础类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆