Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert value type by another value's reflect.Type in Golang

Tags:

go

How to convert value type by another value's reflect.Type in Golang maybe like this:

func  Scan(value interface{}, b string) error {
    converted := value.(reflect.TypeOf(b)) // do as "value.(string)"
    return nil
}

How can do this properly in golang?

like image 793
user1221244 Avatar asked May 20 '14 08:05

user1221244


1 Answers

The only way to get a typed value out of an interface is to use a type assertion, and the syntax is value.(T) where T is a type. There's a good reason for this, because it makes the type of the type assertion expression computable: value.(T) has type T. If instead, you allowed value.(E) where E is some expression that evaluates to a reflect.Type (which I think is the gist of your question), then the compiler has no way to (in general) statically determine the type of value.(E) since it depends on the result of an arbitrary computation.

like image 150
Paul Hankin Avatar answered Oct 11 '22 11:10

Paul Hankin