Go Workspace
Go is designed to work when your code is inside a workspace. The workspace is a folder composed of bin
, pkg
and src
subfolders. In short, create a go
folder with a src
subfolder wherever you expect to put your projects. The workspace defined by $GOPATH
. Simply set export GOPATH=~/gocode
to set the workspace root at ~/gocode
.
Compile
Go is a compiled language. It is compiled to assembly language. go build
compiles the code, but throws away the output. To make your package accessible to the workspace, you need to use go install
to generate a package file in pkg/
folder under the workspace.
go install
compiles source code within a src
folder and generate an executable in $GOPATH/bin/
folder.
go run
is a handy command that compiles and runs your code.
Run
In Go, the entry point to a program has to be a function called main
within a package main
.
Code Formatting
go fmt
command formats your code using Go’s authoritative formatting rules. When you’re inside a project, you can apply the formatting rule to it and all sub-projects via
go fmt ./...
Comment
Go provides C-style /* */
block comments and C++-style //
line comments. Line comments are the norm; block comments appear mostly as package comments, but are useful within an expression or to disable large swaths of code.
The program godoc
processes Go source files to extract documentation about the contents of the package. Comments that appear before top-level declarations, with no intervening newlines, are extracted along with the declaration to serve as explanatory text for the item. The nature and style of these comments determines the quality of the documentation godoc
produces.
Unit test
Go’s unit test lives in the package directory and ends in _test.go
. Tests will be part of the source package, but it won’t be built into the package. When we run go test
, Go compiles everything in the package and synthesize all test functions that begins with Test
.