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