samedi 22 septembre 2018

How to cast a struct to a basic type, rather than the immediate type in 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.




Aucun commentaire:

Enregistrer un commentaire