gpt4 book ai didi

go - 消除类型转换中的重复代码

转载 作者:数据小太阳 更新时间:2023-10-29 03:26:01 26 4
gpt4 key购买 nike

由于我不能在类型切换中使用fallthrough,有什么办法可以在这段代码中合并这两种情况吗?

switch v := moduleSource.(type) {
case Driver:
dec.Decode(&v)
_, _ = ormInstance.Insert(&v)

case Metric:
dec.Decode(&v)
_, _ = ormInstance.Insert(&v)

default:
fmt.Println("unknown type")
}

ORM 调用 ormInstance.Insert() 必须具有正确的结构才能正常工作。

最佳答案

类型开关中允许使用类型列表,如 Go spec 中所定义.

switch v := moduleSource.(type) {
case *Driver, *Metric:
// v has the same type as moduleSource
dec.Decode(v)
_, _ = ormInstance.Insert(v)

default:
fmt.Println("unknown type")
}

关于go - 消除类型转换中的重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41661356/

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