跳至主要内容

[Note] Golang Snippets

go snippets @ Github

在 Terminal 產生問題,並取得使用者在 Terminal 輸入的內容

keywords: bufio, fmt, log, os, strings

add_person.go @ GitHub: protobuf

func main() {
// 建立 Reader
r := bufio.NewReader(os.Stdin)

// 詢問姓名
fmt.Println("What's your name?")
name, err := r.ReadString('\n')
if err != nil {
log.Fatalln(err)
}
name = strings.TrimSpace(name)

// 詢問年齡
fmt.Println("What's your age?")
age, err := r.ReadString('\n')
if err != nil {
log.Fatalln(err)
}
age = strings.TrimSpace(age)

// 輸出結果:Hello Aaron, you are 32 years old
fmt.Printf("Hello %s, you are %s years old", name, age)
}

enum

enum with string value

package mode

// modified from: https://github.com/gotify/server/blob/master/mode/mode.go
package mode

type Mode string

var (
Dev Mode = "dev"
Prod Mode = "prod"
Test Mode = "test"
)

var mode = Dev // mode 預設值是 Dev

func Set(newMode Mode) {
mode = newMode
}

func Get() Mode {
return mode
}

main

func main() {
// 取得預設的 mode
currentMode := mode.Get()
fmt.Println("currentMode", currentMode) // dev

// 使用 Set 更新 mode
mode.Set(mode.Prod)
updatedMode := mode.Get()
fmt.Println("updatedMode", updatedMode) // prod

// 轉成字串
modeString := string(updatedMode)
fmt.Println("modeString", modeString) // prod
}

enum with integer value

enum @ pjchender github > go-snippets

package

package enum

import "fmt"

type OrderStatus int

const (
Created OrderStatus = iota
Paid
Canceled
Shipped
)

var orderStatues = map[OrderStatus]string{
Created: "Created",
Paid: "Paid",
Canceled: "Canceled",
Shipped: "Shipped",
}

func (w OrderStatus) String() (string, error) {

text, ok := orderStatues[w]
if !ok {
return "", fmt.Errorf("no available enum of %v", w)
}

return text, nil
}

func (w OrderStatus) ToInt() int {
return int(s)
}

main

func main() {
receiveData = 0
orderStatus, err := OrderStatus(receiveData).String()
fmt.Println(orderStatus) // "Created"
}