Please enable Javascript to view the contents

初次見面 Golang

· ☕ 2 分钟 · 🐔 Redd Tsai
🏷️
  • #Go
  • 第一次發 Golang 的文章,當然要來個 hello world 作為開場。

    Installation

    安裝 Go。

    1
    2
    3
    
    brew install go@1.14
    
    go version
    

    First Package

    環境準備就緒後,來建立第一個 Go Project。

    1
    2
    3
    4
    
    mkdir hello
    cd hello
    touch hello.go
    code .
    

    example. hello.go

    1
    2
    3
    4
    5
    6
    7
    
    package main
    
    import "fmt"
    
    func main() {
    	fmt.Println("hello world")
    }
    

    來看到 hello.go 的內容,作個基本認識:

    1. package
      • 命名(naming),一個 .go 檔,除了 main 之外,第一步是替 package 命名,請先參考 package names 瞭解命名規則,必免在引用 package 時產生困擾。
      • 空間(space),相同目錄中的 .go 檔,藉由 package 來組織和編譯,就像其它語言 namespace 的功用。
    2. import
      • 導入 local 或 remote 套件。
    3. function
      • 名稱(name),func name()
      • 輸入(input),func(input)
      • 輸出(output),func() (output)

    執行 hello.go 顯示 hello world

    1
    
    go run hello.go
    

    Modules

    接著是套件管理,從 Go 1.11 開始有了 Go Modules,這裡只要先有個觀念,不論 local 或 remote 套件請使用 Go Modules 來管理。

    Testing

    當 Package 完成後,別忘了 go 有個很好用的 test framework。
    example. hello_test.go

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    package main
    
    import (
    	"testing"
    )
    
    func TestHello(t *testing.T) {
    	t.Log("hello world")
    }
    

    執行測試

    1
    
    go test -v
    

    Tour of Go

    如果你是第一次學習程式,對 Go 毫無概念,可從線上 Tour 開始。
    Tour of Go

    Editer

    介紹一個免費且功能強大的程式碼編輯器 Visual Studio Code,讓你編輯專案更有效率。

    1. 下載安裝
      官網下載最新的安裝程式,執行並安裝。
    2. 安裝 Go 擴充工具
      開啟 Visual Studio Code,移至 Extensions 頁面,安裝 Go。

    Reference

    GO

    分享

    蔡文杰
    作者
    Redd Tsai
    Backend Developer