Search code examples
gostructreturnreturn-type

Can I return an anonymous struct from a method?


Let's say I've got a struct such as:

type Tmp struct {
    Number int 
    Text   string
}

Is it possible to have a method that returns an anonymous struct? something like:

func (t Tmp) MyStruct() struct {
    return struct {
        myVal       string
    }{
        "this is my val"
    }
}

I tried the code above but I'm getting an error. Is this possible to achieve any other way?


Solution

  • Yes it's possible, but your function signature is syntactically incorrect. struct is a keyword, not a type.

    It's valid like this:

    func (t Tmp) MyStruct() struct {
        myVal string
    } {
        return struct {
            myVal string
        }{
            "this is my val",
        }
    }
    

    Testing it:

    var t Tmp
    fmt.Printf("%+v", t.MyStruct())
    

    Output will be (try it on the Go Playground):

    {myVal:this is my val}
    

    As you can see, it's not very convenient as you have to repeat the struct definition in the composite literal when returning the value. To avoid that, you may use named result:

    func (t Tmp) MyStruct() (result struct {
        myVal string
    }) {
        result.myVal = "this is my val"
        return
    }
    

    This outputs the same. Try this one on the Go Playground.

    But the easiest is to define a type you want to return, and everything will be simple:

    type MS struct {
        myVal string
    }
    
    func (t Tmp) MyStruct() MS {
        return MS{myVal: "this is my val"}
    }
    

    Try this one on the Go Playground.