如何将结构转换为基本类型,而不是Go中的立即类型?

I need to cast an interface of an unknown immediate type to a known basic type.

Example

package main

import (
    "fmt"
    "reflect"
)

type A struct {
    foo string
}

type B A

func main() {
    bS := B{foo: "foo"}
    bI := reflect.ValueOf(bS).Interface()
    fmt.Println(bI)

    aS := bI.(A)
    fmt.Println(aS)
}

When this code is run, it, understandably, panics with the following message

panic: interface conversion: interface {} is main.B, not main.A

In this example:

  • type B is unknown to the code receiving the interface bI
  • type B is guaranteed to be an alias to type A, which is known.

Edit: I can't use type aliasing here, because this means that type B would become just another way to write type A, so I'd lose all the custom methods I have defined on type B.

You can solve this with type aliasing (released in Go1.9).

package main

import (
    "fmt"
    "reflect"
)

type A struct {
    foo string
}

type B = A

func main() {
    bS := B{foo: "foo"}
    bI := reflect.ValueOf(bS).Interface()
    fmt.Println(bI)

    aS := bI.(A)
    fmt.Println(aS)
}

N.B. type B = A makes is so that cast will work.

the only way I know to go to the first struct is aS := A(bI.(B)) is reversing the process. Hope it helps