How to define multi type as one type in golang

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

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)
}

huangapple
  • 本文由 发表于 2023年7月8日 09:32:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76641009.html
匿名

发表评论

匿名网友

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

确定