When we invoke go run file.go
or go test
, the compiler will check the following file sequentially.
This is my observation and I don't have any valid resource to validate it.
- file *.go (file.go)
- check
import
-ed module
- check
- go.mod
- check file exist
- if missing, error: go.mod file not found
- check module name
- check
require
-ed module (imported) from the first step- if missing in go.mod, error: no required module
- to create and download package:
go get
- this will add list of required modules into
go.mod
- this will also create
go.sum
- go.sum
- check file exist
- if missing, error: missing go.sum
- to create:
go get
go get
is recommended thango mod download
since go get will download all required packages
- back to file *.go (file.go)
- check if it is package
main
- if not, error: is not a main package
- check if it is package
new mengalokasikan memory, tapi tidak menginisialisasikan nilai, default adalah 0 (zero) atau string kosong. Umum new digunakan untuk:
- arrays
- structs
- nilai lainnya (int, float64, etc)
Ada 3 cara mengalokasikan memory and menginisialisasi nilai:
// c type is *Circle (means pointer to Circle struct)
c := new(Circle)
c := &Circle{}
c := Circle{
radius: 10
}
// type *[]int, *sequence = nil, cap = 0 and len = 0
var sequence *[]int = new([]int)
Untuk tipe data native, hanya bisa menggunakan new
i := new(int) // valid
i := &int // invalid
Fungsi make adalah inisialisasi nilai, berbeda dengan new yang fungsinya adalah alokasi memory. make hanya bisa digunakan untuk
- slice
- map
- channels.
// type []int, v = [0 0 0 0 0] => it first create 50 int and slicing it to 5 => len = 5, cap = 50
var v []int = make([]int, 5, 50)
fmt.Println(v) // [0 0 0 0 0]
fmt.Println(len(v)) // 5
fmt.Println(cap(v)) // 50
- using slice
package main
import (
"fmt"
)
func main() {
byteArray := []byte{'G', 'O', 'L', 'A', 'N', 'G'}
str1 := string(byteArray[:])
fmt.Println("String =",str1)
}
- using
bytes
package
package main
import (
"fmt"
"bytes"
)
func main() {
byteArray := []byte{'H', 'E', 'L', 'L', 'O'}
str1 := bytes.NewBuffer(byteArray).String()
fmt.Println("String =",str1)
}
- using
fmt.Sprintf()
package main
import (
"fmt"
)
func main() {
byteArray := []byte{'J', 'A', 'N', 'E'}
str1 := fmt.Sprintf("%s", byteArray)
fmt.Println("String =",str1)
}
var err error
// using pkg/fmt -> this actually will use pkg/errors
err = fmt.Errorf("cannot divide by zero")
fmt.Printf("Error: %v", err.Error())
// using pkg/errors
err = errors.New("invalid parameters")
fmt.Printf("Error: %v", err.Error())