在Golang中,有没有一种方法可以忽略错误返回值?

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

Is there a way to ignore an error return value in Golang?

问题

我正在尝试在Go语言中初始化一个结构体,其中一个值是通过strconv.Atoi("val")将字符串转换为int类型并返回错误。

我的问题是:在Golang中有没有一种忽略错误返回值的方法?

ts := &student{
    name: td[0],
    ssn: td[2],
    next: students.next,
    age: strconv.Atoi(td[1]),
}

这段代码会报错:

multiple-value strconv.Atoi() in single-value context

如果我加上错误变量err,虽然我不想在结构体中包含它,但会出现使用未在结构体中定义的方法的错误。

英文:

I'm trying to initialize a struct in Go, one of my values is being which returns both an int and an error if one was encountered converted from a string using strconv.Atoi("val").

My question is : Is there a way to ignore an error return value in Golang?

ts := &student{
    name: td[0],
    ssn: td[2],
    next: students.next,
    age: strconv.Atoi(td[1]),
  }

which gives the error

multiple-value strconv.Atoi() in single-value context

if I add in the err, which i don't want to include in my struct, I will get an error that I am using a method that is not defined in the struct.

答案1

得分: 11

你可以使用左侧的_来忽略返回值,但是在你的示例中使用“复合字面量”初始化样式时,我认为没有任何方法可以这样做。

例如,我可以这样做:returnValue1, _ := SomeFuncThatReturnsAresultAndAnError(),但是如果你在你的示例中尝试这样做:

ts := &student{
    name: td[0],
    ssn: td[2],
    next: students.next,
    age, _: strconv.Atoi(td[1]),
  }

它也会生成一个编译器错误。

英文:

You can ignore a return value using _ on the left hand side of assignment however, I don't think there is any way to do it while using the 'composite literal' initialization style you have in your example.

IE I can do returnValue1, _ := SomeFuncThatReturnsAresultAndAnError() but if you tried that in your example like;

ts := &student{
    name: td[0],
    ssn: td[2],
    next: students.next,
    age, _: strconv.Atoi(td[1]),
  }

It will also generate a compiler error.

huangapple
  • 本文由 发表于 2016年3月16日 02:57:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/36019815.html
匿名

发表评论

匿名网友

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

确定