This question already has answers here:
Multiple values in single-value context

(5个答案)


4年前关闭。




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返回多个值,因此我无法将其直接分配给struct属性。如果它是一个变量,我可以使用下划线忽略第二个值。我可以为结构做类似的事情吗?

最佳答案

strconv.Atoi可能会失败,您必须处理此失败。如果绝对不可能发生此类失败,则可以编写一个函数func MustAtoi(s string) int,该函数会在失败时崩溃,并在结构初始化中使用该函数。

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

您很可能应该重新考虑错误处理。

关于go - 将多值分配给结构文字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33605586/

10-12 00:21
查看更多