iT邦幫忙

2025 iThome 鐵人賽

DAY 2
0

嗨!大家好~

完成 Go 的安裝之後,就要來認識 Go 的一些基本語法,然後印出大家寫程式時都很熟悉的老朋友 Hello World!

實作 Go 的基本指令

在開始之前我們先在建立一個專案資料夾,並將路徑轉至此資料夾底下:

mkdir <your file name> && cd <your file name>

ex:
mkdir app && cd app

接著輸入以下指令初始化module

go mod init <your file name>

ex:
go mod init app

執行初始化步驟之後,會自動產生一個 go.mod 檔案,內容如下:

go module app

go 1.25.0

再來,可以先加入一些外部套件,看看剛剛產生的 go.mod 會有什麼變化,這邊先安裝 Gin

go get github.com/gin-gonic/gin

👉 Gin 是 Go 語言的網頁框架,它非常輕量、高效能之外,也很好上手。( Gin 官網:https://gin-gonic.com/zh-tw/

安裝完成之後,你會發現剛剛的 go.mod 檔案多了好多東西,而且多了一個 go.sum 檔案,如下圖。
go.mod 新增加的東西就是我們剛剛安裝的 library;而go.sum 則是用來驗證 library 是否完整。

https://ithelp.ithome.com.tw/upload/images/20250916/2017822349YfivpkGg.png

這時候我們再輸入以下指令,你會發現剛剛在 go.mod 檔案裡面新增加的東西都被刪掉了!
原因是這些 library 目前沒有被使用到,所以就被刪除了, go mod tidy 會自動刪除沒用到的 library,並下載缺少的套件。

    go mod tidy

我們可以輸入以下指令查看目前有哪些 library 或 package:

    go list -m all

以上這樣就跑完了基本的流程,再來要來實作印出 Hello World!


  1. 在剛剛建立的專案資料夾底下建立一個 main.go 檔案:

    package main
    import "fmt"
    func main() {
        fmt.Println("Hello World")
    }
    
  2. 初始化:

    go mod init app
    go mod tidy
    
  3. 執行:

    go run main.go
    
  4. 輸出:
    hello-world.png

這樣就成功執行專案了!Hello world 總是非常的平易近人 👍


總結

上面的流程落落長,做完可能不知道自己做了什麼,我來總結一下重點~

前面有提到 module 一詞,是 Go 很重要的概念。它在 Go 1.11 時推出,並且在 Go 1.16 之後成為預設,取代了舊的 GOPATH 模式。

Go Module 讓每個專案可以獨立管理 library,而不再被過去的 GOPATH 限制住。
簡單來說,Go Module 就是 Go 的「 library 管理系統 」。

go.mod :紀錄專案中用了哪些 library。
go.sum:驗證 library 的完整性。

  • 常用指令:

    • go mod init → 建立 module
    • go get → 安裝 library
    • go mod tidy → 整理已安裝的 library(刪除沒用到的,新增有用到的)
    • go list -m all → 查看安裝的 library 有哪些
  • 啟動專案時步驟:

    1. 初始化

      go mod init <file name>
      go mod tidy
      
    2. 執行

      go run <file name>
      

以上就是 Go Module 很重要的概念,明天會再繼續介紹基本語法,明天見囉~


上一篇
Day1 - 從前端到後端:我為什麼選擇 Go?
下一篇
Day3 - Go 基本語法介紹-1:變數、基本型態、條件與迴圈
系列文
Go,一起成為全端吧!—— 給前端工程師的 Golang 後端學習筆記5
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言