Go: setInterval

記錄一下Golang的setInterval方法 package main import ( "log" "time" ) func main() { ticker := time.NewTicker(5 * time.Second) defer ticker.Stop() for ; true; <-ticker.C { log.Println("hello") } } Ref: https://stackoverflow.com/questions/32705582/how-to-get-time-tick-to-tick-immediately ...

Go: 邏輯運算子

在Go的規格書裡面有寫到以下敘述 && conditional AND p && q is "if p then q else false" || conditional OR p || q is "if p then true else q" ! NOT !p is "not p" 這是一種叫做Short-circuit evaluation的優化方法 以p && q來說,如果p是false的話其實就保證這個結果一定是false,這時候就不用特別再去看q了。反過來說p || q也是一樣的,如果p是true,q是什麼值都不會影響最終結果。 package main import "fmt" func TrueHere() bool { fmt.Println("call TrueHere") return true } func FalseHere() bool { fmt.Println("call FalseHere") return false } func main() { fmt.Println("&&") if FalseHere() && TrueHere() {} /* output: && call FalseHere */ fmt.Println("||") if TrueHere() || FalseHere() {} /* output: || call TrueHere */ } ...

Go: 讀取相對檔案路徑

檔案結構 ❯ tree . . ├── config │ └── config.go ├── config.yml └── main.go 1 directory, 3 files 理論上會把讀取相關檔案的邏輯寫在config/config.go, 這時候的路徑如果能以呼叫的地方為出發點會比較不容易搞混 main.go package main import ( "log" ) func main() { err := config.LoadConfig("./config.yml") if err != nil { log.Fatal(err) } } config/config.go package config import ( "fmt" "io/ioutil" "path/filepath" "runtime" ) func LoadConfig(path string) error { _, file, _, _ := runtime.Caller(1) content, err := ioutil.ReadFile(filepath.Join(filepath.Dir(file), path)) if err != nil { return err } fmt.Println(string(content)) // for test here // 解構config之類的操作 ... return nil } 即便未來多了其他類似cmd/somecmd/main.go的檔案需要用到config, 也不用擔心呼叫時的資料夾位置, 放心的寫呼叫的檔案本身的相對路徑就對了(σ゚∀゚)σ ...