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);
}
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 (_).
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.
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.
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.
Does this work?
cwd, error := os.Getwd();
if error == nil {
fmt.Printf(cwd);
}
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With