Golang 从文件中读取数据并指出缺失值

我正在解析一个包含整数值的 csv 文件,其中一些可能会丢失:


1,2,3

1,2,

1,2,3

在我的代码中,我用数据填充了一个结构:


type Line struct {

    One   *int

    Two   *int

    Three *int

}

我目前处理缺失值的猜测是使用指向 an 的指针int来显示值是否缺失:


// if nil, then no value in file

l := &Line{}

// read and parse...

l.Three = nil

但是,使用这种方法会使评估变得*int麻烦:


l := &Line{}

// NOT POSSIBLE, NOT COMPILING (cannot use 5 (type int) as type *int in assignment)

l.One = 5

// FEELS WRONG, BUT WORKS

tmpInt := 5

l.One = &tmpInt

如何处理缺失的整数值?


Smart猫小萌
浏览 265回答 1
1回答

跃然一笑

您可以使用一个函数Line{}从[]string一个简单的示例构建您的:func NewLine(s []string) (l *Line) {&nbsp; &nbsp; fmt.Println(len(s))&nbsp; &nbsp; if len(s) < 2 {&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; l = &Line{}&nbsp; &nbsp; if i, err := strconv.Atoi(s[0]); err == nil {&nbsp; &nbsp; &nbsp; &nbsp; l.One = &i&nbsp; &nbsp; }&nbsp; &nbsp; if i, err := strconv.Atoi(s[1]); err == nil {&nbsp; &nbsp; &nbsp; &nbsp; l.Two = &i&nbsp; &nbsp; }&nbsp; &nbsp; if len(s) == 3 {&nbsp; &nbsp; &nbsp; &nbsp; if i, err := strconv.Atoi(s[2]); err == nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; l.Three = &i&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go