Like Share Discussion Bookmark Smile

J.J. Huang   2025-06-20   Getting Started Golang 07.套件   瀏覽次數:次   DMCA.com Protection Status

Go | 打造一個實用工具套件

💬 簡介

完成一系列關於 Go 套件的設計、管理與實務應用後,是時候動手打造一個實用的自定義工具套件。
透過實戰操作,能進一步深化模組化開發的概念與技巧。

本篇將帶你一步步建立一個名為 strutil 的字串處理套件,涵蓋常用的字串判斷與轉換邏輯,並實作實際應用範例。

圖片來源:Gophers


🔱 套件目標

建立一個簡單但實用的字串輔助工具套件 strutil,提供以下功能:

  • 判斷字串是否為空白
  • 將字串轉換為蛇底線格式(snake_case)
  • 將字串轉換為駝峰式命名(camelCase)

🗂️ 專案目錄結構

1
2
3
4
5
myapp/
├── go.mod
├── main.go
└── strutil/
└── strutil.go
  • strutil/:自定義的工具套件
  • main.go:測試並呼叫 strutil 套件
  • go.mod:模組初始化設定

🛠️ 建立 strutil 套件

建立 strutil/strutil.go,實作核心邏輯:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// strutil/strutil.go
package strutil

import (
"strings"
"unicode"
)

// IsBlank 判斷字串是否為空或僅包含空白字元
func IsBlank(s string) bool {
return len(strings.TrimSpace(s)) == 0
}

// ToSnakeCase 將字串轉為 snake_case
func ToSnakeCase(s string) string {
var result []rune
for i, r := range s {
if unicode.IsUpper(r) {
if i > 0 {
result = append(result, '_')
}
result = append(result, unicode.ToLower(r))
} else {
result = append(result, r)
}
}
return string(result)
}

// ToCamelCase 將字串轉為 camelCase
func ToCamelCase(s string) string {
parts := strings.Split(s, "_")
for i := range parts {
if i == 0 {
continue
}
if len(parts[i]) > 0 {
parts[i] = strings.ToUpper(parts[i][:1]) + parts[i][1:]
}
}
return strings.Join(parts, "")
}

📝以上函式皆以大寫開頭,代表為「公開識別符」,可供其他套件呼叫。


🚀 測試與使用套件

main.go 中引入 strutil 套件,測試其功能:

1
2
3
4
5
6
7
8
9
10
11
12
13
// main.go
package main

import (
"fmt"
"myapp/strutil"
)

func main() {
fmt.Println(strutil.IsBlank(" ")) // true
fmt.Println(strutil.ToSnakeCase("HelloWorld")) // hello_world
fmt.Println(strutil.ToCamelCase("hello_world")) // helloWorld
}

初始化模組(若尚未完成):

1
go mod init myapp

🧪 延伸練習:加入單元測試

撰寫測試檔案 strutil/strutil_test.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package strutil

import "testing"

func TestIsBlank(t *testing.T) {
if !IsBlank(" ") {
t.Error("應為 true,但得到 false")
}
}

func TestToSnakeCase(t *testing.T) {
got := ToSnakeCase("HelloWorld")
want := "hello_world"
if got != want {
t.Errorf("預期 %s,但得到 %s", want, got)
}
}

func TestToCamelCase(t *testing.T) {
got := ToCamelCase("hello_world")
want := "helloWorld"
if got != want {
t.Errorf("預期 %s,但得到 %s", want, got)
}
}

執行測試:

1
go test ./strutil

🎯 總結

本篇透過實作 strutil 套件,學會以下幾點:

  • ✅ 如何撰寫自定義工具套件
  • ✅ 公開函式與模組管理的實務操作
  • ✅ 使用 go test 撰寫並執行單元測試
  • ✅ 應用套件於主程式中呼叫與整合

這不僅讓程式碼更模組化與可重用,也為開發大型專案奠定良好基礎。

最後建議回顧一下 Go | 菜鳥教學 目錄,了解其章節內容。


註:以上參考了
Go