Unused variable and _ (underscore) variable

498 views
Skip to first unread message

Sanoop

unread,
Oct 2, 2011, 3:32:02 AM10/2/11
to golang-nuts
Hi List,

I am a newbie on Go, till now I am enjoying Go and I would like to
enjoy in future also -:)

I have come with error like - Variable is declared and not in Use,
thats make sense to me.

But what if some bunch of code ran on the conditions where I might or
might not need the variable.

I tried to print _ variable and got "cannot use _ as value" Error.
What is the role/reason to declare _ variable in Go?


Thanks,
Sanoop

chris dollin

unread,
Oct 2, 2011, 4:02:13 AM10/2/11
to Sanoop, golang-nuts
On 2 October 2011 08:32, Sanoop <sanoop...@gmail.com> wrote:

> But  what if some bunch of code ran on the conditions where I might or
> might not need the variable.

Can you give an example?

The language counts any read from the variable as a "use",
if I understand it correctly. It doesn't matter if it's, say, only in
one branch of an `if`.

> I tried to print _ variable and got "cannot use _ as value" Error.
> What is the role/reason to declare _ variable in Go?

When you need a variable name in a declaration or assignment
but you're not actually interested in its value.

Chris

--
Chris "allusive" Dollin

Sanoop

unread,
Oct 2, 2011, 4:25:14 AM10/2/11
to golang-nuts
> Can you give an example?

I am not good writing code in Go, but pseudo code like -

if(diementionCount == 2){
set x, set y
drow(2d Image)
}

if(diementionCount == 3){
set x, set y, set z
drow(3d Image)
}

in this scenario if(diementionCount == 2) variable z is unused but
define.

On Oct 2, 1:02 pm, chris dollin <ehog.he...@googlemail.com> wrote:

peterGo

unread,
Oct 2, 2011, 4:47:57 AM10/2/11
to golang-nuts
Sanoop,

As long as it's used somewhere. For example,

package main

func main() {
x, y := 1, 2
n := 0
if x == 1 {
n = x
}
if x > 0 {
n = x + y
}
n++
}

Peter

Sanoop

unread,
Oct 2, 2011, 4:52:49 AM10/2/11
to golang-nuts
Thanks Peter, Chris,

I got your point.

Thanks a lot.
Reply all
Reply to author
Forward
0 new messages