return from a function

15 views
Skip to first unread message

brainman

unread,
Mar 25, 2010, 1:07:54 AM3/25/10
to golang-nuts
This program:

package main

func test() int {
if true {
return 1
} else {
return 0
}
}

func main() {
print(test())
}

fails to compile:

8g -o test.8 test.go
test.go:7: function ends without a return statement

Is that by design?


Alex

Russ Cox

unread,
Mar 25, 2010, 1:13:46 AM3/25/10
to brainman, golang-nuts

brainman

unread,
Mar 25, 2010, 1:21:31 AM3/25/10
to golang-nuts

On Mar 25, 4:13 pm, Russ Cox <r...@google.com> wrote:
> http://code.google.com/p/go/issues/detail?id=65

Thanks for the pointer.

But I still not sure about how should my code look:

func test() int {
if true {
return 1
} else {
return 0
}
}

or

func test() int {
if true {
return 1
}

return 0
}

or

func test() int {
if true {
return 1
} else {
return 0
}

return 0 // just to shut up compiler
}

considering "if" branches are equally important.

What do you prefer?


Alex

Andrew Gerrand

unread,
Mar 25, 2010, 1:30:13 AM3/25/10
to brainman, golang-nuts
The middle case, for sure. The less nesting, the easier it is to read.

> To unsubscribe from this group, send email to golang-nuts+unsubscribegooglegroups.com or reply to this email with the words "REMOVE ME" as the subject.
>

brainman

unread,
Mar 25, 2010, 1:34:01 AM3/25/10
to golang-nuts

On Mar 25, 4:30 pm, Andrew Gerrand <a...@google.com> wrote:
> The middle case, for sure. The less nesting, the easier it is to read.
>

Ok. Thank you.


Alex

Paladin R. Liu

unread,
Mar 25, 2010, 9:40:47 PM3/25/10
to golang-nuts
Why don't you try to write your code like these?
---
func test() int {
result := 0;

if true {
result = 1;
}

return result;
}
---
It is easier to read, isn't it?


Paladin

Steven

unread,
Mar 26, 2010, 1:00:16 AM3/26/10
to Paladin R. Liu, golang-nuts
On Thu, Mar 25, 2010 at 9:40 PM, Paladin R. Liu <bug...@gmail.com> wrote:
Why don't you try to write your code like these?
---
func test() int {
 result := 0;

 if true {
   result = 1;
 }

 return result;
}
---
It is easier to read, isn't it?


Paladin

No.
1) Go provides named return variables for a reason.
2) Go allows multiple returns for a reason.

Trying to avoid using the language because of old adages in the culture of another language is a fantastic way to obfuscate your code.
Reply all
Reply to author
Forward
0 new messages