Why does golang prohibit assignment to same underlying type when one is a native type?
go
Solution
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.
Problem
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..