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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With