Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"variable declared and not used" compilation error

I am learning Google's new language Go. I am just trying stuff out and I noticed that if you declare a variable and do not do anything with it the go compiler (8g in my case) fails to
compile with this error: hello.go:9: error declared and not used. I was suprised at this since most language compilers just warn you about unused variables but still compile.

Is there anyway I can get around this? I checked the documentation for the compiler and I don't see anything that would change this behaviour. Is there a way to just delete error so that this will compile?

package main

import "fmt"
import "os"

func main()
{
     fmt.Printf("Hello World\n");
     cwd, error := os.Getwd();
     fmt.Printf(cwd);
}
like image 510
Isaiah Avatar asked Nov 11 '09 23:11

Isaiah


People also ask

How do you avoid declared but not used?

To avoid this error – Use a blank identifier (_) before the package name os. In the above code, two variables name and age are declared but age was not used, Thus, the following error will return. To avoid this error – Assign the variable to a blank identifier (_).

How do you use global variables in Golang?

Golang Global VariableAfter declaration, a global variable can be accessed and changed at any part of the program. In the example above, we declare a global variable called “global”. We then set the value for the variable inside the multiply function. Any part of the program can change the value of a global variable.


4 Answers

You could try this:

cwd, _ := os.Getwd();

but it seems like it would be better to keep the error like in Jurily's answer so you know if something went wrong.

like image 69
Matthew Crumley Avatar answered Sep 29 '22 12:09

Matthew Crumley


this can make development a bit of a pain. sometimes i run code that has variables declared but not used (but will be used).

in these cases i simple do this:

fmt.Printf("%v %v %v",somevar1,somevar2,somevar3)

and there, they are "used".

i'd like to see a flag to the go tools that lets me suppress this error while developing.

like image 32
Brad Clawsie Avatar answered Sep 29 '22 13:09

Brad Clawsie


Does this work?

cwd, error := os.Getwd();
if error == nil {
    fmt.Printf(cwd);
}
like image 36
György Andrasek Avatar answered Sep 29 '22 14:09

György Andrasek


You can find out what the error is by importing "fmt" and using

cwd, err := os.Getwd();
if err != nil {
    fmt.Printf("Error from Getwd: %s\n", err)
}

What does it print?

like image 42
Russ Cox Avatar answered Sep 29 '22 12:09

Russ Cox