2

I am trying to use type assertion in golang. with direct assertion there is no problem.

a, ok := i.(MyStruct)

but when I use reflection

b, ok := i.(reflect.TypeOf(i))

I got an error. What was a problem with that? and How to deal with it?

Full Code:

package main

import (
     "fmt"
     "reflect"
)

type MyStruct struct {
    field string
}

func main() {
    var i interface{} = MyStruct{field:"Thanks"}

    a, ok := i.(MyStruct)
    fmt.Println(a, ok)

    t := reflect.TypeOf(i)
    fmt.Println(t)

    b, ok := i.(t)
    fmt.Println(b, ok)
}

Thank for your answers.

Night Owl
  • 99
  • 7
  • 1
    Possible duplicate of of [1](https://stackoverflow.com/questions/27900568/golang-type-assertion-using-reflect-typeof), [2](https://stackoverflow.com/questions/48991710/how-to-use-a-reflect-type-to-perform-a-type-assertion) –  Jan 30 '20 at 06:51

0 Answers0