tags:

views:

371

answers:

3

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);
}
+3  A: 

Does this work?

cwd, error := os.Getwd();
if error == nil {
    fmt.Printf(cwd);
}
Jurily
+4  A: 

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.

Matthew Crumley
Thanks. For some reason the error returned by os.Getwd() is not nil but cwd is still the correct string. Weird. Maybe the error is never nil.
DoR
A: 

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?

Russ Cox