登录
首页 >  Golang >  Go问答

从核心函数中检索未知类型的空值

来源:stackoverflow

时间:2024-03-01 18:27:23 208浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《从核心函数中检索未知类型的空值》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

我有一个返回 interface 的函数,有时我的函数应该返回 nil。但我想返回请求类型的 nil

我确实通过创建另一个函数来处理这个问题。

func GetNilOfType(needType string) interface{}{
    switch needType {
        case "string":
            return ""
        case "int":
        case "int32":
        case "int64":
            return 0
        case "float32":
        case "float64":
            return 0.0
        //... other types
    }
    return nil
}

我的问题:是否有 core 函数 来处理它,或者我应该创建自己的函数?

ps。抱歉我的表情复杂。我希望你明白我的意思:)


解决方案


没有标准库函数可以使用指定为字符串名称的类型。您可以按照 icza 评论中的建议使用示例值和 reflect.Zero

func getniloftype(valueoftype interface{}) interface{}{
     return reflect.zero(reflect.typeof(valueoftype)).interface()
}

这样称呼它:

x := getniloftype(int32(123))

Run it on the playground

您需要编写自己的函数来按名称指定类型。在实现中使用地图:

var zeros = map[string]interface{}{
    "string": "",
    "int16":  int16(0),
    "int8":   int8(0),
    "int":    int(0),
    "int32":  int32(0),
    "int64":  int64(0),
    // ... and so on
}

func getniloftype(name string) interface{} {
    x, ok := zeros[name]
    if !ok {
        panic("oops")
    }
    return x
}

以上都没有比使用文字作为类型的零更好:

x := int32(0)
y := (*mytype)(nil)
...

没有核心(内置)函数可以返回给定类型的零值。但是,您可以使用 reflect 编写自己的代码。像这样的东西:

func zero(sample interface{}) interface{} {
    return reflect.zero(reflect.typeof(sample))
}

您可以像这样使用它:

zero("somestring").(string)

您确实需要提供一个从中提取类型的值;您无法像使用 makenew 那样直接提供类型。

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>