英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论