Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

go build works fine but go run fails

I have a few files in the main package under one directory:

main.go config.go server.go

When I do: "go build" the program builds perfect and runs fine. When I do: "go run main.go" it fails.

Output:

# command-line-arguments ./main.go:7: undefined: Config ./main.go:8: undefined: Server 

The symbols that are undefined are structs and they are capitalised so should be exported.

My Go version: go1.1.2 linux/amd64

like image 748
Roel Van Nyen Avatar asked Jan 22 '14 20:01

Roel Van Nyen


People also ask

Does go run also build?

go run is just a shortcut for compiling then running in a single step. While it is useful for development you should generally build it and run the binary directly when using it in production. There must be more to it than that - if I time the println in a helloworld, it runs faster with go run than compiled.

How do I run a go file after build?

From the command line in the hello directory, run the go build command to compile the code into an executable. From the command line in the hello directory, run the new hello executable to confirm that the code works.

What happens when you run go build?

go build builds the command and leaves the result in the current working directory. Above program will be able to turn into an executable file that will always print out “Hello World”. If we want our program to run again, we don't have to compile the program again, we simply run the executable file.

Where does go build output go?

go build builds the command and leaves the result in the current working directory. go install builds the command in a temporary directory then moves it to $GOPATH/bin .


1 Answers

This should work

go run main.go config.go server.go 

Go run takes a file or files and it complies those and only those files which explains the missing symbols in the original post.

like image 186
Nick Craig-Wood Avatar answered Sep 22 '22 19:09

Nick Craig-Wood