gpt4 book ai didi

go - 使用 go sql 时,在每种类型中重写 Scan 和 Value 方法时避免重复代码

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

Golan SQL 和 Gorp 期望所有类型都包含附加到该类型的 Scan 和 Value 方法,以便将行读取到结构中。这会在我的项目中添加大量样板代码,即使这些方法可以通用化也是如此,因为我正在将 JSON 写入此列。

type Type1 struct {
Type2 Type2
Type3 Type3
Type4 Type4
}

type Type2 struct { some primitives... }
type Type3 struct { some primitives... }
type Type4 struct { some primitives... }


func (q Type2) Value() (driver.Value, error) {
return json.Marshal(q)
}

func (q *Type2) Scan(src interface{}) error {
source, _ := src.([]byte)
if string(source) == "null" {
return nil
}
return json.Unmarshal(source, q)
}

func (q Type3) Value() (driver.Value, error) {
return json.Marshal(q)
}

func (q *Type3) Scan(src interface{}) error {
source, _ := src.([]byte)
if string(source) == "null" {
return nil
}
return json.Unmarshal(source, q)
}

func (q Type4) Value() (driver.Value, error) {
return json.Marshal(q)
}

func (q *Type4) Scan(src interface{}) error {
source, _ := src.([]byte)
if string(source) == "null" {
return nil
}
return json.Unmarshal(source, q)
}

有没有办法避免为我的每个结构定义所有那些相同的值和扫描方法?

表格应该是这样的:

Table: Type1
-----------------------
ROW Type2 Type3 Type4
1 {"name": "MyName"} {"other": "bla"} {"other": "bla"}

我尝试使用 @danicheeta 推荐的组合:

type Base struct {} 
type Type2 struct { Base, some primitives... }

func (q Base) Value() (driver.Value, error) {
return json.Marshal(q)
}

func (q *Base) Scan(src interface{}) error {
source, _ := src.([]byte)
if string(source) == "null" {
return nil
}
return json.Unmarshal(source, q)
}

但是如果我对数据库执行插入,结果是:

Table: Type1
-----------------------
ROW Type2 Type3 Type4
1 {} {} {}

同样,如果我已经在数据库中“手动”插入了​​这个:

Table: Type1
-----------------------
ROW Type2 Type3 Type4
1 {"name": "MyName"} {"other": "bla"} {"other": "bla"}

然后尝试执行 select * from Type1 我得到:

Type1: {
Type2: {}
Type3: {}
Type4: {}
}

最佳答案

解决方法:

type Base struct {}

type Type2 struct { Base, some primitives... }
type Type3 struct { Base, some primitives... }
type Type4 struct { Base, some primitives... }

func (q Base) Value() (driver.Value, error) {
return json.Marshal(q)
}

func (q *Base) Scan(src interface{}) error {
source, _ := src.([]byte)
if string(source) == "null" {
return nil
}
return json.Unmarshal(source, q)
}

请注意,嵌入到结构中的 Base 前面不应有 var(我的意思是 type Type2 struct { b Base, some primitives...})

关于go - 使用 go sql 时,在每种类型中重写 Scan 和 Value 方法时避免重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52177007/

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