gpt4 book ai didi

go - 在 if 条件内创建类型

转载 作者:IT王子 更新时间:2023-10-29 02:37:24 25 4
gpt4 key购买 nike

要求:

type A struct {//some code}
type B struct {//some code}

func getData(db string) interface{} {
if db == "dbA" { // problem with this if condition
type C A
} else {
type C B
}
var byteData []byte
query := //cassandra query object
iter := query.Iter()
for iter.Scan(&byteData) {
myObject := new(C)
err := proto.Unmarshal(byteData, myObject)
objects = append(objects, myObject)
}
return objects
}

基本上,我不想在循环内编写 if 条件。但是 myObject 声明在 C 的范围之外。

替代方法:我试过将 myObject 的类型设置为 proto.Message,但这给了我错误“无效的内存地址或零指针取消引用”

myObject := new(proto.Message)
err := proto.Unmarshal(byteData, myObject)
objects = append(objects, myObject)

另一种选择:我也不确定使用相同的变量是否有效(因此我每次都在循环内尝试创建一个新变量)

PS:这不需要太多的Cassandra知识

感谢帮助。谢谢!

编辑 1:我想要完成的是从数据库中获取几行。但是因为我有多个包含非常相似数据的表,所以我想以一种非常优化的方式在一个函数中完成它。我想要获取的值以字节为单位存储,我正在使用 proto 将其转换为 Golang 对象。

编辑 2:proto.Unmarshal 需要第二个参数是 proto.Message 类型。因此我不能使用空接口(interface)。 (类型A和B都实现了proto.Message)

编辑 3:你可以在“github.com/golang/protobuf”找到原型(prototype)。我用它来将对象转换成字节,然后再转换回对象。!

最佳答案

在Go的类型系统中,你想实现的是不能直接完成的。

但是,在 interface{} 和一流函数值的帮助下,我们可以非常优雅地完成它。

为此,我们声明一个新的构造函数,而不是声明一个新的type C:

var newC func() interface{}
if true {
newC = func() interface{} {
c := new(A)
return c
}
} else {
newC = func() interface{} {
c := new(B)
return c
}
}

然后,在循环中,将 myObject := new(C) 更改为 myObject := newC()。完成了。

示例:https://play.golang.org/p/dBKBYrLqi_P

编辑:

因为你需要参数是一个proto.Message,我猜它是一个interface,你可以把它转换成proto.Message .

所以基本上您可以将代码重写为:

type A struct {//some code}
type B struct {//some code}

func getData(db string) interface{} {
var newC func() interface{}
if true {
newC = func() proto.Message {
c := new(A)
return c
}
} else {
newC = func() proto.Message {
c := new(B)
return c
}
}
var byteData []byte
query := //cassandra query object
iter := query.Iter()
for iter.Scan(&byteData) {
myObject := newC()
err := proto.Unmarshal(byteData, myObject)
objects = append(objects, myObject)
}
return objects
}

关于go - 在 if 条件内创建类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51237867/

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