英文:
Assigning values to pointer types in a go struct
问题
在尝试将数据结构输入到数据库行(使用goqu)时,为了处理空值,我定义了一个类似的结构体:
type datain struct {
id *float32 `db:"id"`
tempr *float32 `db:"temperature"`
}
由于这些值都来自字符串,我编写了一个函数来将字符串转换为float32类型:
func stringToFloat32(instr string) float32 {
value, err := strconv.ParseFloat(instr, 32)
if err != nil {
log.Crit("error converting to float", "stringToFloat32", err)
}
return float32(value)
}
然而,当我尝试使用以下代码时:
var datastruct datain
*datastruct.id = stringToFloat32("1234.4")
我得到一个错误:无效的地址或空指针解引用。这在某种程度上对我来说是有道理的,但无论我怎么尝试,我都无法弄清楚如何在存在值的情况下给这些结构字段赋值。
我尝试使用这种机制来允许在输入的CSV字符串中某个字段没有值时使用空值。
也许我正在用一种复杂的方式来做这件事?我肯定在某个地方语法有误。
进一步的调查发现,我可能需要一个new()
函数来为每个指针分配一个真实的变量... 但我仍然觉得这样做有点复杂。
英文:
In an attempt to handle null values when trying to input a struct of data to a database row (using goqu) I've defined a struct similar to
type datain struct {
id *float32 `db:"id"`
tempr *float32 `db:"temperature"`
}
and as these are all coming from strings I've made a function
func stringToFloat32(instr string) float32 {
value, err := strconv.ParseFloat(instr, 32)
if err != nil {
log.Crit("error converting to float", "stringToFloat32", err)
}
return float32(value)
}
to convert the strings to float32's... however when I try and use
var datastruct datain
*datastruct.id = stringToFloat32("1234.4")
I get an error, invalid address or nil pointer dereference
which sort of makes sense to me.. but try as I might, I can't work out how to put a value in these structure fields if one exists.
I'm trying to use this mechanism to allow nulls when there is no value for one of the fields in the input csv string.
Maybe I'm doing this the hard way? I definitely have the syntax wrong somewhere.
Further digging.. seems I might need a new() function to assign a real variable to each pointer... Still can't help but feel this is doing things the hard way though.
答案1
得分: 3
当你定义一个没有任何初始化的datain
变量时,id
的值是nil
,这意味着你不能对它进行解引用。
var datastruct datain
id := stringToFloat32("1234.4")
datastruct.id = &id
英文:
When you defined a datain
variable without any initialization, the value of the id
was nil, which means you couldn't de-reference it.
var datastruct datain
id := stringToFloat32("1234.4")
datastruct.id = &id
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论