Casting from one pointer to pointer type to another in Golang error

后端 未结 2 476
逝去的感伤
逝去的感伤 2021-02-02 15:02

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 *         


        
相关标签:
2条回答
  • 2021-02-02 15:41

    Here are two functionally equivalent working versions of your program.

    package main
    
    type mypint *int
    
    func set(a *mypint) {
        i := int(5)
        *a = &i
    }
    
    func main() {
        var k *int
        set((*mypint)(&k))
        print(*k)
    }
    

    http://play.golang.org/p/l_b9LBElie

    package main
    
    type myint int
    
    func set(a *myint) *myint {
        i := myint(5)
        a = &i
        return a
    }
    
    func main() {
        var k *int
        k = (*int)(set((*myint)(k)))
        print(*k)
    }
    

    http://play.golang.org/p/hyaPFUNlp8

    0 讨论(0)
  • 2021-02-02 15:54

    Here's my analysis.

    (**myint)(&k) -- cannot convert &k (type **int) to type **myint:

    type **int and type **myint are unnamed pointer types and their pointer base types, type *int and type *myint, don't have identical underlying types.

    If T (*int or *myint) is a pointer type literal, the corresponding underlying type is T itself.

    (*myint)(k) -- can convert k (type *int) to type *myint:

    type *int and type *myint are unnamed pointer types and their pointer base types, type int and type 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) to type myint:

    type int and type myint 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).

    Here's the underlying type example from the Types section revised to use integers and int pointers.

    type T1 int
    type T2 T1
    type T3 *T1
    type T4 T3
    

    The underlying type of int, T1, and T2 is int. The underlying type of *T1, T3, and T4 is *T1.

    References:

    The Go Programming Language Specification

    Conversions

    Types

    Properties of types and values

    Type declarations

    Predeclared identifiers

    Pointer Type

    0 讨论(0)
提交回复
热议问题