Home > Backend Development > Golang > How to define multiple types as one type in golang

How to define multiple types as one type in golang

WBOY
Release: 2024-02-09 10:03:19
forward
664 people have browsed it

How to define multiple types as one type in golang

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!

Question content

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)
}
Copy after login

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)

Workaround

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
}
Copy after login

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)
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template