syntax clarification

78 views
Skip to first unread message

John Wilson

unread,
Jun 6, 2013, 9:06:04 AM6/6/13
to golan...@googlegroups.com
Hi folks,

Can someone explain to me why the following doesn't compile:

package main
import "fmt"

func getValue() (string, int) {
return "my value", 1
}

func main() {
var val string
if true {
val, status := getValue()
if status != 1 {
fmt.Println("error")
} else {
val = "go nothing"
}
fmt.Println(val)
}

But this does:

package main
import "fmt"

func getValue() (string, int) {
return "my value", 1
}

func main() {
var val string
var status int
if true {
val, status = getValue()
if status != 1 {
fmt.Println("error")
} else {
val = "go nothing"
}
fmt.Println(val)
}

Cheers
John 

Jan Mercl

unread,
Jun 6, 2013, 9:14:00 AM6/6/13
to John Wilson, golang-nuts
On Thu, Jun 6, 2013 at 3:06 PM, John Wilson <wilso...@gmail.com> wrote:
> Can someone explain to me why the following doesn't compile:
>
> package main
> import "fmt"
>
> func getValue() (string, int) {
> return "my value", 1
> }
>
> func main() {
> var val string
> if true {
> val, status := getValue()
> if status != 1 {
> fmt.Println("error")
> }
> } else {
> val = "go nothing"
> }
> fmt.Println(val)
> }


The error message "prog.go:12: val declared and not used" is clear and
complete. The if statement has it's own scope withing the brackets.
There 'val is declared and not used' in that scope.

-j

John Wilson

unread,
Jun 6, 2013, 10:00:41 AM6/6/13
to golan...@googlegroups.com, John Wilson
Thanks Jan.
Also got further clarification from the docs : /doc/effective_go.html#redeclaration

John Wilson

unread,
Jun 6, 2013, 10:02:22 AM6/6/13
to golan...@googlegroups.com, John Wilson
Reply all
Reply to author
Forward
0 new messages