Starting a New Go Project
If you are new to Go, here is the basic process for setting up a new project and building/running it. This assumes that you have already installed Go as described in the previous blog post.
First, create a working directory for the project, and change into it:
mkdir ~/myproject
cd ~/myproject
Then, use your favorite text editor or IDE to create a Go program, with any name that ends in .go, for example main.go:
vim main.go
Here is the canonical simplest program, that just prints a message:
package main
import "fmt"
func main() {
fmt.Println("Welcome to Go")
}
You could compile this program directly, by typing:
go build main.go
Then, you will see a new file called main in the directory, and you can run this executable by typing:
./main
However, I recommend that you set up the program as a module, so you can
use go build
to build a program from multiple source files, and run tests.
This also plays nicely with IDEs:
go mod init fastdatascience.io/myprogram
Replace the URL with your own (or with github.com if creating an open-source module that others can pull in). The module name (“myprogram” in the example above) should be the same name as the directory, so IDEs like LiteIDE will build correctly. Note the URL is optional, and you don’t need the slash if you omit the URL.
Then, you can just type:
go build
to create the executable. As before type ./main
to run the program.
You can also type go run
to build and run the program in one step (but
this does not keep the executable).
Finally, you should initialize the directory with Git and make a commit with you your new program:
git init
git add main.go
git commit -a -m "Initial commit of new Go program
You can also create a respository in GitHub, and sync the repository to to GitHub.
That’s it, you now have a project to build upon.