Go Commands
go fmt
: format the .go
files in the current directorygo fmt ./...
: format everything in the current and children directory.go run <FILE_NAME>
: build and run codego build <FILE_NAME>
: compile and build a binary file, can be executed by $ ./<FILE_NAME>
go env
: show all environment variables for gogo install <FILE_NAME>
:
- For an executable:
- compiles the program
- names the executable the folder name holding the code
- puts the executable in **workspace/bin** `$GOPATH/bin`
- For a package
- compiles the package
- puts the executable in **workspace/pkg** `$GOPATH/pkg`
Go Workspace
GOPATH: Points to your workspace
GOROOT: Points to your binary installation of Go
Packages
Every Go program is made up of packages.
In Go, a name is exported if it begins with a capital letter. For example, Pizza
is an exported name, as is Pi
, which is exported from the math
package.
1 | func main() { |
Functions
Type comes after the variable name.
Go’s return values may be named. If so, they are treated as variables defined at the top of the function.
A return
statement without arguments returns the named return values. This is known as a “naked” return.
1 | func add(x int, y int) int { |
Variables
The var
statement declares a list of variables; as in function argument lists, the type is last.
A var
statement can be at package or function level. We see both in this example.
1 | var c, python, java bool |
Inside a function, the :=
short assignment statement can be used in place of a var
declaration with implicit type.
Outside a function, every statement begins with a keyword (var
, func
, and so on) and so the :=
construct is not available.
1 | func main() { |
Basic Types
1 | bool |
The int
, uint
, and uintptr
types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems. When you need an integer value you should use int
unless you have a specific reason to use a sized or unsigned integer type.
1 | import ( |
Type Conversion
The expression T(v)
converts the value v
to type T
.
1 | var i int = 42 |
When declaring a variable without specifying an explicit type (either by using the :=
syntax or var =
expression syntax), the variable’s type is inferred from the value on the right hand side.
When the right hand side of the declaration is typed, the new variable is of that same type:
1 | var i int |
But when the right hand side contains an untyped numeric constant, the new variable may be an int
, float64
, or complex128
depending on the precision of the constant:
1 | i := 42 // int |
Constants
Constants are declared like variables, but with the const
keyword.
Constants can be character, string, boolean, or numeric values.
Constants cannot be declared using the :=
syntax.
1 | func main() { |
Numeric constants are high-precision values.
An untyped constant takes the type needed by its context.