Can anyone tell my why this wouldn’t compile?
package main
type myint int
func set(a **myint) {
i := myint(5)
*a = &i
}
func main() {
var k *int
set( (**myint)(&k) ) // cannot convert &k (type **int) to type **myint
print( *k )
}
My reasoning so far is this. All types in Golang are different, but it allows to convert from one type to another with C-like cast syntax as long as underlying types are identical. In my example, converting ‘int’ to ‘myint’ is not a problem. ‘*int’ to ‘*myint’ isn’t either. It’s when you have pointer to pointer problems arise. I’ve been stuck on this for the second day now. Any help is appreciated.
Here’s my analysis.
(**myint)(&k)— cannot convert&k(type **int) totype **myint:type **intandtype **myintare unnamed pointer types and their pointer base types,type *intandtype *myint, don’t have identical underlying types.If T (
*intor*myint) is a pointer type literal, the corresponding underlying type is T itself.(*myint)(k)— can convertk(type *int) totype *myint:type *intandtype *myintare unnamed pointer types and their pointer base types,type intandtype myint(type myint int), have identical underlying types.If T (
int) is a predeclared type, the corresponding underlying type is T itself. If T (myint) is neither a predeclared type or nor a type literal, T’s underlying type is the underlying type of the type to which T refers in its type declaration (type myint int).(myint)(*k)— can convert*k(type int) totype myint:type intandtype myinthave identical underlying types.If T (
int) is a predeclared type, the corresponding underlying type is T itself. If T (myint) is neither a predeclared type or nor a type literal, T’s underlying type is the underlying type of the type to which T refers in its type declaration (type myint int).Here’s the underlying type example from the Types section revised to use integers and int pointers.
The underlying type of
int,T1, andT2isint. The underlying type of*T1,T3, andT4is*T1.References:
The Go Programming Language Specification
Conversions
Types
Properties of types and values
Type declarations
Predeclared identifiers
Pointer Type