Golang 入門
Go Programming Language, tutorial
參考文章
Golang 官方文件
Golang 入門的入門
Golang 編譯參數說明
未驗證參考文章
Golong 常用指令
// 查詢 Golang 環境參數
go env
// 用於建立 Golang 專案初始化產生 go.mod 檔案。
go mod init sample-app
// 編譯組建 Release 模式的應用程式。
go build -ldflags "-s -w" -o sample-app.exe
//※ 其中 -ldflags "-s -w" 表示移除 debug 關聯符號檔,可增加安全性。
Golang go.mod
檔是什麼
go.mod
檔是什麼Go 的go.mod
檔作用如下。
go.mod
是用來定義module的文件。Go module的根目錄中會有一個go.mod
檔,其為一個UTF-8編碼的文字檔,用來標明此module的module path、使用的go版本及管理module的依賴。
專案的go.mod
類似Java Maven的pom.xml
或Gradle的build.gradle
;Node.js npm或Yarn的package.json
,是管理依賴module的配置文件。
下面是一個簡單的go.mod
檔。
module sample-app
go 1.18
require (
github.com/dariubs/percent v0.0.0-20200128140941-b7801cf1c7e2
gopkg.in/yaml.v2 v2.4.0
)
Go 產生不同平台的執行檔
Go 本身就是一個跨平台的程式語言,所以將專案編譯成其他作業系統能夠執行的檔案也是有支援的,今天就來筆記一下,如何在 Windows 作業系統編譯 Mac 的執行檔案。
指令紀錄
SET GOOS=linux&SET GOARCH=amd64&go build -ldflags "-s -w" -o cttool-app
// 用 SET 指令變更目標OS與目標ARCH,再執行build就能組建出linex版程式。
參考文章
Golang 基本語法範例
基本語法
package main
import ("fmt")
func main() {
//## Hello world
fmt.Println("Hello world. 哈囉世界好。")
//## Array 和 Sllice
names := []string {"it","home"}
fmt.Println(names)
//## 印出後面幾個字的子字串
game := "it home iron man"
fmt.Println(game[8:])
//## 流程控制
gender := "female"
// if syntax
if gender == "male" {
fmt.Println("我是男生")
} else {
fmt.Println("我不是男生")
}
// switch syntax, 其中沒有 break 關鍵字
switch gender {
case "female":
fmt.Println("you are a girl.")
case "male":
fmt.Println("you are a boy.")
default:
fmt.Println("you arx a X-man. ")
}
//## Loop
// for-loop syntax
for i:=0; i<10; i++ {
fmt.Println(i)
}
// key value pairs
kvs := map[string]string {
"name": "it home",
"website": "https://ithelp.ithome.com.tw",
}
// foreach syntax
for key,value := range kvs {
fmt.Println(key, value)
}
//## Object
// 用字首大小寫, 判別是否是public / private
type Post struct {
ID int
Title string
Author string
Difficulty string
}
p := Post {
ID: 12345678,
Title: "上班不要混",
Author: "Rely",
Difficulty: "Beginner",
}
fmt.Println(p)
fmt.Println(p.Author)
// 用 map[key]interface 語法
// 效果等同 anonymous type
p2 := map[string]interface{} {
"ID": 87654321,
"Title" : "下班加減學點Golang",
"Author": "Nobody",
"Difficulty":"Beginner",
}
fmt.Println(p2)
fmt.Println(p2["Author"])
}h
初步模組化: func
package main
import (
"fmt"
"time"
)
// 匯入多個模組
func main() {
say("hello")
}
func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(500 * time.Millisecond)
fmt.Println(s)
}
}
Last updated