Go語言學習筆記
阿新 • • 發佈:2020-12-16
Hello, world!
package main
import "fmt"
func main() {
fmt.Println("Hello, world!")
}
起步
建立並執行程式碼
為Go專案建立一個資料夾
mkdir hello
cd hello
在資料夾中建立 hello.go
檔案,並在檔案中放入以下程式碼
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
在程式碼中:
- 宣告一個
main
包(包是對函式分組的一種方式)- 匯入 Go 標準庫裡的
fmt
包,它包含了用於格式化文字,包括列印到控制檯的函式。- 實現一個
main
函式來列印訊息到控制檯。當執行程式碼時,預設會執行main
函式。
使用 go run
命令執行程式碼
$ go run hello.go
Hello, World!
呼叫外部包中的程式碼
使用 pkg.go.dev 來查詢已釋出的模組
在 hello.go
中匯入 rsc.io/quote
並呼叫該包中的函式
package main
import "fmt"
import "rsc.io/quote"
func main() {
fmt.Println(quote.Go())
}
執行 go mod init
go.mod
檔案
$ go mod init hello
go: creating new go.mod: module hello
執行 hello.go
檢視呼叫外部包產生的資訊
$ go run hello.go
go: finding module for package rsc.io/quote
go: found rsc.io/quote in rsc.io/quote v1.5.2
Don't communicate by sharing memory, share memory by communicating.