Sẽ có 2 kiểu program trong Go:
src
: Contains Go source files.pkg
: Contains package objectsbin
: Contains Go executable commands.We will keep source codes in directory named $GOPATH/src/github.com/user/project1
so we can call our package in another one by using:
import ("github.com/user/project1")
In order to build and install a package, you run:
go install $GOPATH/src/github.com/user/project1
or more simply go install github.com/user/project1
The command builds the package and produces a executable command in our workspace's bin
directory.
Go package name is the last element in import path, an executable command must always use package main
, for example the "math/rand"
package will contains a file start with package rand
.
In Go, a name is exported if it begins with capital letter, for example Pi
in math
package.
When importing packages, you can refer only to package's exported name, any unexported name can only be accessible inside the package.
var <variable_name> <type>
Examples:
var x1, x2 int = 1, 2
var y *int
var z [3]int
func <function_name>(args1 type1, args2 type2) <function_type>
Examples:
func main(x int, str []string) int
func main(int, []string) int
Notes:
:=
can be used to replace var
keyword.var p *int
i := 42
p = &i
fmt.Println(*p) // read i through the pointer p
*p = 21 // set i through the pointer p
Example:
type Vertex struct {
X int
Y int
}
func main() {
v := Vertex{1, 2}
v.X = 4
fmt.Println(v.X)
}
Declare a slice:
letters := []string{"a", "b", "c", "d"}
Declare a slice using make
func (func make([]T, len, cap) []T)
:
s = make([]byte, 5, 5)
// s == []byte{0, 0, 0, 0, 0}
var x int = 10
var y float64 = float64(x)
var z uint = uint(y)
Examples:
const Pi = 3.14
Constant cannot be declared using the :=
syntax
Examples:
//For loop
sum := 0
for i := 0; i < 1000; i ++ {
sum += i
}
//While loop
sum := 0
for sum < 1000 {
sum += sum
}
//Infinity loop
for {
//Do sth
}
//Switch
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("Good morning!")
case t.Hour() < 17:
fmt.Println("Good afternoon.")
default:
fmt.Println("Good evening.")
}
defer
ensure a function be performed after its surrounding function returns, usually defer
is used as cleanup actions.func b() {
for i := 0; i < 4; i++ {
defer fmt.Print(i)
}
}
This will returns "3210"
Example:
f := createFile("/tmp/defer.txt")
defer closeFile(f)
writeFile(f)
Go futher Go programming language specifications Effective Go