Go 語言筆記(1) — Program Structure(上)

Jade Chen
Jade Chen
Oct 29, 2018 · 11 min read

「就如同畫畫前要先描繪骨幹⋯⋯」

Photo by Simon Goetz on Unsplash

【學習無帝王之路?】


【導言】


【開發環境與建議先備知識】


【壹、Naming】

簡單規則

// Go has 25 keywords (reserved)
// that may be used only where the syntax permits
// they can't be used as names
break default func interface select
case defer go map struct
chan else goto package switch
const fallthrough if range type
continue for import return var
// if you want to redeclare one of them
// beware of the potential for confusion
Constants: true false iota nilTypes: int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64 uintptr
float32 float64 complex128 complex64
bool byte rune string error
Functions: make len cap new
append copy close delete
complex real imag
panic recover

更多細節

Go開發者的慣例


【貳、Declarations】

主要的四種宣告方式

範例1.1

攝氏轉華氏溫度

【參、Variables】

四種常見的var宣告方式

var boilingC = 100               // int
var b, f, s = false, 1.5, "boo" // bool, float64, string
var f, err = os.Open(fileName) // return file, error
var s string    // ""
var a, b, c int // 0, 0, 0
/*
Rules:
1. 0 for numbers.
2. false for booleans.
3. "" for strings.
4. nil for interface & reference types(slice, pointers, map, channel, function).
*/
i := 100 // an intin, err := os.Open(infile)
// ...
out, err := os.Create(outfile)
// Should not be confused:
a, b := 0, 1 // short variable declaration
a, b = b, a // swap values by tuple assignment

指針(Pointers)

x := "Hello"
p := &x // p of type *string
fmt.Println(*p) // "Hello"
*p = "Hi" // 等同於 x = "Hi"
fmt.Println(x) // "Hi"

範例1.2

使用pointer和不使用的比較

new

// 以下左右兩邊做的事是完全一樣的,皆將p設為一個指向0的地址,最後print出0。
p := new(int) var dummy int
fmt.Println(*p) p = &dummy
fmt.Println(*p)

Lifetime

// x escapes from f               // y does not escape from g
// -> heap allocated // -> stack allocated
var global *int func f() { func g() {
var x int y:= new(int)
x = 1 *y = 1
global = &x }
}

【肆、Assignments】

scale = 5
*p = "Hi"如果p = &x(p是x的地址),則*p會等於 x(p地址指向的值就是x),此時如果賦予*p不一樣的值,則x也會一起改變。
parents.areHappy = true
count[i] = count[i] * scale // equivalent to count[i] *= scale
scale++ // scale = 6
scale-- // scale = 5

Tuple Assignmnet

Assignability

animals := []string{"dog", "cat", "bird"}
/* which implicitly assigns
animals[0] = "dog"
animals[1] = "cat"
animals[2] = "bird". */

【小結】


餐後點心

整個程式都是我的咖啡館

Python和Golang的教學Blog

Thanks to Jack Shiba.

Jade Chen

Written by

Jade Chen

NTUEE119 | Blockchain TA | NTU Sunrise

整個程式都是我的咖啡館

Python和Golang的教學Blog