英文:
How to define multi type as one type in golang
问题
以下是翻译好的内容:
func GetFailedReasonAndErr(xxx) (string, error) {
...
}
func AnyFailed(args ...func() (string, error)) (string, error) {
for _, arg := range args {
if err := arg(); err != nil {
return err
}
}
return "", nil
}
func main() {
reason, err := AnyFailed(func() (string, error) { return GetFailedReasonAndErr(yyy) }, func() (string, error) { return GetFailedReasonAndErr(zzz) })
println(reason, err)
}
上面的代码无法编译,因为args ...(string, error)
是不允许的。我可以将(string, error)
定义为一种类型吗?或者有更好的方法吗?(可以使用结构体吗?)像这样:
type reasonAndError struct {
reason string
err error
}
英文:
func GetFailedReasonAndErr (xxx) (string, error){
...
}
func AnyFailed (args ...(string, error)) {
for _, arg := range args {
if arg.error != nil {
return arg
}
}
}
func main () {
reason, err := AnyFailed(GetFailedReasonAndErr(yyy), GetFailedReasonAndErr(zzz))
println(reason, err)
}
code above is unable to be complied, because "args ...(string, error)" is not allowed.
can I define (string, error) as one type ? or any better way ?(may use struct?)
like :
type reasonAndError (string, error)
答案1
得分: 2
可以将(string, error)定义为一个类型吗?
不可以,Go语言没有元组(tuples)的概念。
可以使用结构体(struct)来实现,声明一个结构体类型,语法如下:
type reasonAndError struct {
reason string
err error
}
然后,可以这样使用:
func GetFailedReasonAndErr(xxx) reasonAndError {
// ...
}
func AnyFailed(args ...reasonAndError) (string, error) {
for _, arg := range args {
if arg.err != nil {
return arg.reason, arg.err
}
}
return "", nil
}
func main () {
reason, err := AnyFailed(GetFailedReasonAndErr(yyy), GetFailedReasonAndErr(zzz))
println(reason, err)
}
英文:
> can I define (string, error) as one type ?
No, not with that syntax. Go does not have tuples.
> (may use struct?) like : type reasonAndError (string, error)
Yes, declare a struct type and use that. The syntax for declaring struct types is as follows:
type reasonAndError struct {
reason string
err error
}
Then, to use it, you can do:
func GetFailedReasonAndErr(xxx) reasonAndError {
// ...
}
func AnyFailed(args ...reasonAndError) (string, error) {
for _, arg := range args {
if arg.err != nil {
return arg.reason, arg.err
}
}
return "", nil
}
func main () {
reason, err := AnyFailed(GetFailedReasonAndErr(yyy), GetFailedReasonAndErr(zzz))
println(reason, err)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论