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

huangapple go评论72阅读模式
英文:

Golang read data from file and indicate a missing value

问题

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

1,2,3
1,2,
1,2,3

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

type Line struct {
    One   *int
    Two   *int
    Three *int
}

我目前的想法是使用指向 int 的指针来处理缺失的值,以便显示该值是否缺失:

// 如果为 nil,则表示文件中没有值
l := &Line{}
// 读取和解析...
l.Three = nil

然而,使用这种方法会使得对 *int 的赋值变得麻烦:

l := &Line{}
// 不可行,无法编译(无法将类型为 int 的 5 用作类型为 *int 的赋值)
l.One = 5
// 感觉不对,但是可以工作
tmpInt := 5
l.One = &tmpInt

如何处理缺失的整数值?

英文:

I am parsing a csv file which contains integer values, some of them might be missing:

1,2,3
1,2,
1,2,3

In my code I'm populating a struct with the data:

type Line struct {
    One   *int
    Two   *int
    Three *int
}

My current guess to handle missing values would be to use a pointer to an int in order to show whether the value is missing:

// if nil, then no value in file
l := &Line{}
// read and parse...
l.Three = nil

However, using this approach makes assingment to *int cumbersome:

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

How to handle missing integer values?

答案1

得分: 1

你可以使用一个函数来根据[]string构建你的Line{},这是一个简单的示例:

func NewLine(s []string) (l *Line) {
    fmt.Println(len(s))
    if len(s) < 2 {
        return
    }
    l = &Line{}
    if i, err := strconv.Atoi(s[0]); err == nil {
        l.One = &i
    }
    if i, err := strconv.Atoi(s[1]); err == nil {
        l.Two = &i
    }
    if len(s) == 3 {
        if i, err := strconv.Atoi(s[2]); err == nil {
            l.Three = &i
        }
    }
    return
}

你可以从这个示例中了解如何使用函数来构建Line{}对象。

英文:

You could use a function to build your Line{} from a []string, a simple example:

func NewLine(s []string) (l *Line) {
	fmt.Println(len(s))
	if len(s) &lt; 2 {
		return
	}
	l = &amp;Line{}
	if i, err := strconv.Atoi(s[0]); err == nil {
		l.One = &amp;i
	}
	if i, err := strconv.Atoi(s[1]); err == nil {
		l.Two = &amp;i
	}
	if len(s) == 3 {
		if i, err := strconv.Atoi(s[2]); err == nil {
			l.Three = &amp;i
		}

	}
	return
}

huangapple
  • 本文由 发表于 2014年8月10日 23:22:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/25230047.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定