jszwec / csvutil

csvutil provides fast and idiomatic mapping between CSV and Go (golang) values.
MIT License
944 stars 62 forks source link

[Bug?] Struct of Ints Fails to Unmarshal Second Field #65

Closed neilwhitlow closed 1 year ago

neilwhitlow commented 1 year ago

Apologies if I'm missing something obvious as I'm still relatively new with Go, so highly possible this is user error.

Trying to follow the simple Unmarshal example with a struct that has 2 int fields and the second one is always zero.

I have tried with all positive integers in the second column of the csv and it makes no difference, I'm always seeing zero for the mod field.

Code

Link to Playground

type ScoreModifer struct {
    Score    int `csv:"score"`
    Modifier int `csv:"mod"`
}

var csvInput = []byte(`
score, mod
0, -2
1, -2
2, 0
3, 2
4, 3
`)

func main() {
    var mods []ScoreModifer
    if err := csvutil.Unmarshal(csvInput, &mods); err != nil {
        fmt.Println("error:", err)
    }
    for _, m := range mods {
        fmt.Printf("%+v\n", m)
    }
}

Output

{Score:0 Modifier:0}
{Score:1 Modifier:0}
{Score:2 Modifier:0}
{Score:3 Modifier:0}
{Score:4 Modifier:0}

Expected Output

{Score:0 Modifier:-2}
{Score:1 Modifier:-2}
{Score:2 Modifier:0}
{Score:3 Modifier:2}
{Score:4 Modifier:3}
jszwec commented 1 year ago

You have a space in your header and every row on the second column.

This is not being automatically handled. You may want to look into Decoder.NormalizeHeader and Decoder.Map to trim whitespace

jszwec commented 1 year ago

https://go.dev/play/p/oPubDVuRia6

neilwhitlow commented 1 year ago

Good googly moogly, thanks for this. Cannot believe I didn't try that variation of input.