0

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.

Peter Nunn
  • 2,110
  • 3
  • 29
  • 44
  • Looks like you're trying to apply c/c++ to go. That's not how pointers work in go. You can return a pointer from `stringToFloat` and just `datastruct.id = stringToFloat32("1234.4")` or use the approach from the answer. – super Feb 07 '22 at 03:18

1 Answers1

3

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
littlepoint
  • 114
  • 6