给结构体字面量分配多个值

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

Assign multi-value to struct literal

问题

在Go语言中,有没有办法做到这一点:

segment := Segment{
    CumulativeDistanceMm:    strconv.Atoi(record[9]),
    Length:                  strconv.Atoi(record[1]),
    LinkId:                  strconv.Atoi(record[8]),
    SegmentId:               strconv.Atoi(record[2]),
}

我得到的错误是strconv.Atoi返回多个值,所以我不能直接将其赋值给结构体属性。如果它是一个变量,我可以使用下划线来忽略第二个值。我能在结构体中做类似的事情吗?

英文:

Is there any way in Go to do this:

segment := Segment{
    CumulativeDistanceMm:    strconv.Atoi(record[9]),
    Length:                  strconv.Atoi(record[1]),
    LinkId:                  strconv.Atoi(record[8]),
    SegmentId:               strconv.Atoi(record[2]),
}

The error that I get is that strconv.Atoi returns multiple values so I can't assign it directly to the struct properties. If it was a variable I could use the underscore to ignore the second value. Can I do something similar for structs?

答案1

得分: 0

strconv.Atoi 可能会失败,你需要处理这种失败情况。如果这种失败绝对不可能发生,你可以编写一个函数 func MustAtoi(s string) int,在失败时引发 panic,并在结构体初始化中使用该函数。

在 Go 语言中,常常会进行一些编程而不是使用语法糖或花哨的语法。

很可能你应该重新考虑你的错误处理方式。

英文:

strconv.Atoi can fail and you have to deal with this failure. If such failures are absolutely impossible you would write a function func MustAtoi(s string) int which panics on failure and use that one in your struct initialization.

In Go doing some programming instead of using syntactical sugar or fancy syntax is common.

Most probably you should rethink your error handling.

huangapple
  • 本文由 发表于 2015年11月9日 17:02:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/33605586.html
匿名

发表评论

匿名网友

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

确定