In golang, sometimes we need to define multiple types as one type in order to process data more flexibly. For this problem, PHP editor Xinyi brings a solution to everyone. By using interface types, we can define multiple different types as one type. An interface type can define a set of methods without specifying a specific implementation. In this way, we can implement this interface for multiple types, and then use this interface type for unified operations and processing. This approach not only simplifies the code structure, but also improves the readability and maintainability of the code. Next, let’s take a look at the specific implementation steps!
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) }
The above code cannot be compiled because "args ...(string, error)" is not allowed. Can I define (String, Error) as a type? Or any better way? (Can I use structs?) like : Type reasonanderror(String, Error)
Can I define (String, Error) as a type?
No, this syntax is not used. go doesn't have tuples.
(Can you use a structure?) For example: type reasonanderror (string, error)
Yes, declare a struct type and use it. The syntax for declaring a structure type is as follows:
type reasonanderror struct { reason string err error }
Then, to use it, you do the following:
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) }
The above is the detailed content of How to define multiple types as one type in golang. For more information, please follow other related articles on the PHP Chinese website!