anonymous return types

1,026 views
Skip to first unread message

Petar Maymounkov

unread,
Feb 26, 2011, 10:33:53 AM2/26/11
to golang-nuts
I can have a function

func f() struct{ a, b string }

that returns an anonymous type. But would I write the return
statement?

Thanks,
--P

Petar Maymounkov

unread,
Feb 26, 2011, 10:34:43 AM2/26/11
to golang-nuts
I meant: How would I write the return statement?

John Asmuth

unread,
Feb 26, 2011, 10:42:55 AM2/26/11
to golang-nuts
return struct{a,b string}{"hi","there"}

bflm

unread,
Feb 26, 2011, 10:43:17 AM2/26/11
to golang-nuts
On Feb 26, 4:34 pm, Petar Maymounkov <pet...@gmail.com> wrote:
> I meant: How would I write the return statement?
>
> > I can have a function
>
> > func f() struct{ a, b string }
>
> > that returns an anonymous type. But would I write the return
> > statement?

e.g.:
func f() interface{} {
return struct{i int}{42}
}

Petar Maymounkov

unread,
Feb 26, 2011, 10:44:29 AM2/26/11
to bflm, golang-nuts
Awesome. Thanks all. 

I didn't find this in the doc. Maybe needs updating.

—Petar

Steven

unread,
Feb 26, 2011, 10:59:04 AM2/26/11
to Petar Maymounkov, bflm, golang-nuts
On Sat, Feb 26, 2011 at 10:44 AM, Petar Maymounkov <pe...@csail.mit.edu> wrote:
Awesome. Thanks all. 

I didn't find this in the doc. Maybe needs updating.

—Petar

 ? The return statement is properly documented. You just put "return <expression of return type(s)>", or just "return" if all your return values are named. In this case, you are using a composite literal for the return. You could have used a variable, say:

func f() struct{ a, b string } {
    var ret struct { a, b string }
    // ...
    return ret

or named your return value

func f() struct (ret struct{ a, b string }) {
    ret.a = "mostly"
    ret.b = "harmless"

    return
}

When you say "the Go doc", you have read the go spec, right?

Petar Maymounkov

unread,
Feb 26, 2011, 11:03:50 AM2/26/11
to Steven, bflm, golang-nuts
Right.

Actually, it is probably the "Effective Go" that needs an example.

And the second example you give below is probably worth including 
as well since it potentially saves having to re-type the type def.

—Petar
Reply all
Reply to author
Forward
0 new messages