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