Home > Mobile >  Go return values of different types in methods
Go return values of different types in methods

Time:04-10

I have a struct, and bound some methods to it. I need to have smth like this:

func Start() (*MyStruct or empty struct{}, error)

How can I achieve this? How we deal with functions that can return values of different types in GoLang? Sorry for a dumb question. Searched a lot about Generics but found nothing about them in methods... I understand how we deal with simple functions and generics, but what about methods? Please help! Here is a more wide example:
https://play.golang.com/p/7kPHEVC_G3-

CodePudding user response:

As I can see you want to return the empty struct only on errors. The idiomatic way is to return nil and an error, not an empty struct, like:

func Test() (*CustomStruct, error) {
    cs := &CustomStruct{}
    ...
    err := DoSomething()
    if err != nil {
        return nil, err
    }
    ...
    return cs, nil
}
  • Related