在Golang中,如何通过另一个值的reflect.Type来转换值类型?

huangapple go评论108阅读模式
英文:

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

问题

在Golang中,你可以使用反射(reflect)包来实现根据另一个值的reflect.Type来转换值类型。下面是一个示例代码:

import (
    "reflect"
)

func Scan(value interface{}, b string) error {
    targetType := reflect.TypeOf(value) // 获取目标值的类型
    convertedValue := reflect.ValueOf(b).Convert(targetType) // 将b转换为目标类型
    newValue := convertedValue.Interface() // 获取转换后的新值
    // 继续处理新值...
    return nil
}

在上面的代码中,我们首先使用reflect.TypeOf获取目标值的类型,然后使用reflect.ValueOf(b).Convert(targetType)将b转换为目标类型。最后,使用convertedValue.Interface()获取转换后的新值。你可以在newValue中继续处理新值。

请注意,这种类型转换可能会引发panic,因此你可能需要在代码中添加适当的错误处理机制。

英文:

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?

答案1

得分: 5

从接口中获取一个类型化的值的唯一方法是使用类型断言,语法是value.(T),其中T是一个类型。这样做有一个很好的原因,因为它使得类型断言表达式的类型可计算:value.(T)的类型是T。如果你允许value.(E),其中E是一个求值为reflect.Type的表达式(我认为这是你问题的要点),那么编译器无法(通常情况下)静态确定value.(E)的类型,因为它取决于任意计算的结果。

英文:

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.

huangapple
  • 本文由 发表于 2014年5月20日 16:18:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/23754442.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定