package main
import (
"fmt"
)
type val []byte
func main() {
var a []byte = []byte{0x01,0x02}
var b val = a
fmt.Println(a)
fmt.Println(b)
}
o/p: [1 2] [1 2]
Here, my understanding is that a,b identifier share the same underlying type([]byte). so we can exchange the values b/w 2 variables.
package main
import (
"fmt"
)
type abc string
func main() {
fm := fmt.Println
var second = "whowww"
var third abc = second //compile Error at this line 12
fm(second)
fm(third)
}
In line 12 I'm not able to assign the variable. This Error can be eliminated by using Explicit conversion T(x), I want to understand why we cannot do implicit conversion As both variables share the same underlying-type, but I'm not able to assign it.
can someone explain the reason behind these?
IF possible provide me the good documentation for type conversions between variables, struct types, function parameters.
This is by design. The Go programming language requires assignment between different types to have an explicit conversion.
It might look like you're simply aliasing the string type to have a different name, but you're technically creating a new type, with a storage type of string, there's a subtle difference.
The way you would define an alias in Go (as of 1.9) is subtly different, theres an equals sign.
type abc = string
If there's any confusion as to why Go doesn't have implicit conversions, it might seem silly when you're only dealing with an underlying string type, but with more complex types, it ensures that the programmer knows just by looking at the code that a conversion is happening.
Its especially helpful in debugging an application, particularly when converting between numeric types to know when a conversion is taking place, so that if there is a truncation of bits i.e. uint64
to uint32
, it is obvious to see where that is happening.