Ximeng Zhao:
I have a question. I know the below code snippet will return error due to invalid operation: str + nativeStr (mismatched types MyString and string)
type MyString string
func main() {
str := MyString("Hello")
nativeStr := " World!"
result := str + nativeStr // error happens here
fmt.Println(result)
}
But why it doesn’t throw error when I do str + " World!"
in the fmt.Println()
type MyString string
func main() {
str := MyString("Hello")
fmt.Println(str + " World!")
}
My thought was to add string() around str such as
fmt.Println(string(str) + " World!")
Thank you!
Alistair Mackay:
The compiler is very fussy about trying to mix types without an explicit cast (as in your 3rd code block). They enforce this for clarity of the code.
So
result := str + nativeStr // error happens here
It will refuse to implicitly cast string
to MyString
result := str + " World!" // no error
It will implicitly cast a string literal to MyString
because it knows that MyString
is really just a string.
result := string(str) + " World!"
Unnecessary explicit cast
Same goes for numeric types like int
and float64
. If you add values of these types in any other language, you get a float64 result. Go will refuse the addition unless both values are exactly the same type, i.e. you must cast one of the operands.
var i int = 1
var f float64 = 2.0
_ = i + f // compiler error - no cast
_ = i + 1 // ok to add numeric literal
_ = f + 1 // ok to add numeric literal
Ximeng Zhao:
Thanks @Alistair Mackay, that’s super helpful to know