gpt4 book ai didi

go - 从核心函数获取未知类型的nil值

转载 作者:行者123 更新时间:2023-12-03 10:11:06 25 4
gpt4 key购买 nike

我有一个返回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 function来处理它,还是应该创建自己的函数?
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
您将需要编写自己的函数以按名称指定类型。在实现中使用 map :
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)
...

关于go - 从核心函数获取未知类型的nil值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64203391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com