Task | Code Example | Description |
---|---|---|
Creating a new go project | mkdir myproject | |
Download modules | go mod vendor | https://go.dev/ref/mod#go-mod-vendor |
Cleanup modules | go mod tidy | Ensures that the |
Task | Code Example | Description |
---|---|---|
Build | go build -o mysvc | Build project |
Type | Notes |
---|---|
bool | |
string | |
int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr | |
byte | alias for uint8 |
rune | alias for int32 |
float32 float64 | |
complex64 complex128 |
Variables declared without an explicit initial value are given their zero value.
The expression T(v) converts the value v to the type T.
i := 42 f := float64(i) u := uint(f) |
const Pi = 3.14 |
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.
A var declaration can include initializers, one per variable.
Inside a function, the :=
short assignment statement can be used in place of a var
declaration with implicit type.
package main import "fmt" var c, python, java bool var i, j int = 1, 2 func main() { var i int x := 10 fmt.Println(i, c, python, java, x) } |
The type [n]T
is an array of n
values of type T
.
The expression
var a [10]int
example:
package main import "fmt" func swap(x, y string) (string, string) { return y, x } func main() { a, b := swap("hello", "world") fmt.Println(a, b) } |
A defer statement defers the execution of a function until the surrounding function returns.
The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.
Deferred function calls are pushed onto a stack. When a function returns, its deferred calls are executed in last-in-first-out order.
package main import "fmt" func main() { defer fmt.Println("world") fmt.Println("hello") } |
Task | Code Example | Reference | |
---|---|---|---|
Creating an instance of a struct |
| link | |
Implementing an Interface In this example, we see that AcousticGuitarist and BaseGuitarist both implement the PlayGuitar function. |
| link | |
Casting Interface to Concrete v = i.(T) | v = i.(T) |
Task | Code Example | Reference | |
---|---|---|---|
Testing |
|
Reference | URL |
---|---|
A Tour of Go | https://go.dev/tour/list |
Go Home | https://go.dev |
Go Documentation | https://go.dev/doc/ |
Tutorials | https://go.dev/doc/tutorial/ |
Go by Example | https://gobyexample.com |