Go標準ライブラリのナビゲーション:日常プログラミングのための必須パッケージ
Emily Parker
Product Engineer · Leapcell

Goの標準ライブラリは、開発を効率化する豊富な事前構築済み機能を提供する、その強みの中核です。多くの一般的なタスクには、言語自体にバンドルされたエレガントで効率的なソリューションが見つかります。この記事では、すべてのGo開発者が精通しておくべき6つの基本的なパッケージ:fmt
、os
、io
、time
、strings
、strconv
を探求します。それらのコア機能を探求し、実用的な例でその使用法を実証します。
1. fmt
:フォーマット済みI/O
The fmt
package implements formatted I/O (input/output) with functions analogous to C's printf
and scanf
. It's indispensable for printing messages to the console, formatting strings, and reading user input.
主な関数:
fmt.Println()
: 引数の後に改行を付けて表示します。fmt.Printf()
:%s
(文字列)、%d
(10進整数)、%f
(浮動小数点数)、%v
(値、デフォルトフォーマット)、%T
(型)などの動詞を使用したフォーマット済み印刷。fmt.Sprintf()
: フォーマット指定子に従ってフォーマットし、結果の文字列を返します。fmt.Scan()
,fmt.Scanln()
,fmt.Scanf()
: 標準入力から読み取ります。
例:
package main import "fmt" func main() { name := "Alice" age := 30 salary := 50000.75 // Println を使用した単純な出力 fmt.Println("Hello, Go!") fmt.Println("Name:", name, "Age:", age) // Printf を使用したフォーマット済み出力 fmt.Printf("User: %s, Age: %d years old, Salary: %.2f USD\n", name, age, salary) // Sprintf を使用して、印刷せずに文字列をフォーマットする message := fmt.Sprintf("Welcome, %s! Your ID is %d.", name, 123) fmt.Println(message) // 入力の読み取り(基本的な例) var city string fmt.Print("Enter your city: ") fmt.Scanln(&city) fmt.Println("You live in:", city) }
2. os
:オペレーティングシステムとの対話
The os
package provides a platform-independent interface to operating system functionality. This includes file operations, environment variables, command-line arguments, process management, and more.
主な機能:
- ファイルおよびディレクトリ操作:
os.Create()
,os.Open()
,os.ReadFile()
,os.WriteFile()
,os.Remove()
,os.Mkdir()
,os.Rename()
。 - 環境変数:
os.Getenv()
,os.Setenv()
。 - コマンドライン引数:
os.Args
。 - プロセス情報:
os.Getpid()
,os.Getuid()
。 - 終了ステータス:
os.Exit()
。
例:
package main import ( "fmt" "io/ioutil" "os" ) func main() { // コマンドライン引数へのアクセス fmt.Println("Command-line arguments:", os.Args) if len(os.Args) > 1 { fmt.Println("First argument:", os.Args[1]) } // ファイルの作成と書き込み fileName := "example.txt" err := ioutil.WriteFile(fileName, []byte("Hello from Go!"), 0644) if err != nil { fmt.Println("Error writing file:", err) return } fmt.Println("File created:", fileName) // ファイルからの読み取り content, err := ioutil.ReadFile(fileName) if err != nil { fmt.Println("Error reading file:", err) return } fmt.Println("File content:", string(content)) // 環境変数の取得と設定 os.Setenv("MY_VARIABLE", "GoLang_Rocks") envVar := os.Getenv("MY_VARIABLE") fmt.Println("MY_VARIABLE:", envVar) // ファイルの削除 defer func() { // エラーが発生した場合でもクリーンアップを保証する err := os.Remove(fileName) if err != nil { fmt.Println("Error removing file:", err) } else { fmt.Println("File removed:", fileName) } }() }
注意: ioutil
は新しいGoバージョンで非推奨になりました。ファイル操作には、os
およびio
パッケージから直接関数を使用することをお勧めします(例:os.WriteFile
, os.ReadFile
)。
3. io
:基本的なI/Oプリミティブ
The io
package provides basic interfaces to I/O primitives, primarily focusing on Reader
and Writer
interfaces. These interfaces are fundamental to how Go handles streams of data, allowing for highly flexible and decoupled I/O operations.
主なインターフェースと関数:
io.Reader
: データの読み取り用インターフェース。io.Writer
: データの書き込み用インターフェース。io.Copy()
:Reader
からWriter
へデータをコピーします。io.ReadAll()
:io.Reader
からEOFまですべてのデータを読み取り、バイトスライスとして返します。
例:
package main import ( "bytes" "fmt" "io" "os" "strings" ) func main() { // 例1:文字列からバッファへのコピー reader := strings.NewReader("This is some text to be read.") var buffer bytes.Buffer n, err := io.Copy(&buffer, reader) if err != nil { fmt.Println("Error copying:", err) return } fmt.Printf("Copied %d bytes: %s\n", n, buffer.String()) // 例2:ファイル(io.Reader)から標準出力(io.Writer)への読み取り file, err := os.Open("example.txt") // osパッケージの例からexample.txtが存在すると仮定 if err != nil { fmt.Println("Error opening file:", err) return } defer file.Close() fmt.Println("Content of example.txt via io.Copy to Stdout:") _, err = io.Copy(os.Stdout, file) if err != nil { fmt.Println("Error copying to stdout:", err) } // 例3:すべてのコンテンツをバイトスライスに読み取る r := strings.NewReader("Another string to read fully.") allContent, err := io.ReadAll(r) if err != nil { fmt.Println("Error reading all:", err) } fmt.Printf("ReadAll content: %s\n", allContent) }
4. time
:時間と期間
The time
package provides functionality for measuring and displaying time, including parsing and formatting, durations, and tickers. It's crucial for anything involving dates, times, and scheduling.
主な型と関数:
time.Time
: 特定の時点を表します。time.Duration
: 2つの時点間の経過時間を表します。time.Now()
: 現在のローカル時刻を返します。time.Parse()
: フォーマットされた文字列をtime.Time
オブジェクトに解析します。time.Format()
:time.Time
オブジェクトを文字列にフォーマットします。time.Since()
: 指定された時刻からの経過時間を計算します。time.Sleep()
: 指定された期間、現在のゴルーチンを一時停止します。time.Stamp
,time.RFC3339
など:フォーマットのための事前定義されたレイアウト。
例:
package main import ( "fmt" "time" ) func main() { // 現在時刻の取得 now := time.Now() fmt.Println("Current time:", now) // 時間のフォーマット fmt.Println("Formatted (RFC3339):"); now.Format(time.RFC3339)) fmt.Println("Formatted (Custom):"); now.Format("2006-01-02 15:04:05 Mon")) // MM/DD/YYYY はレイアウト用に 01/02/2006 // 文字列からの時間の解析 timeString := "2023-10-26T10:30:00Z" parsedTime, err := time.Parse(time.RFC3339, timeString) if err != nil { fmt.Println("Error parsing time:", err) return } fmt.Println("Parsed time:", parsedTime) // 時間の算術演算と期間 tomorrow := now.Add(24 * time.Hour) fmt.Println("Tomorrow:", tomorrow) duration := tomorrow.Sub(now) fmt.Println("Duration until tomorrow:", duration) // スリープ(実行の一時停止) fmt.Println("Sleeping for 2 seconds...") time.Sleep(2 * time.Second) fmt.Println("Awake!") // 実行時間の測定 start := time.Now() sum := 0 for i := 0; i < 1000000; i++ { sum += i } elapsed := time.Since(start) fmt.Printf("Calculation took %s\n", elapsed) }
5. strings
:文字列操作
The strings
package provides a rich set of functions for manipulating UTF-8 encoded strings. It's a go-to package for everything from searching and replacing to splitting and joining strings.
主な関数:
strings.Contains()
: 部分文字列が含まれているかチェックします。strings.HasPrefix()
,strings.HasSuffix()
: 接頭辞と接尾辞をチェックします。strings.Index()
,strings.LastIndex()
: 部分文字列のインデックスを見つけます。strings.Replace()
,strings.ReplaceAll()
: 部分文字列の出現を置き換えます。strings.Split()
,strings.Join()
: 文字列を文字列のスライスに分割し、文字列スライスを単一の文字列に結合します。strings.ToLower()
,strings.ToUpper()
: 大文字小文字を変換します。strings.TrimSpace()
,strings.TrimPrefix()
,strings.TrimSuffix()
: 先頭/末尾の文字を削除します。
例:
package main import ( "fmt" "strings" ) func main() { text := " Go programmers love Go " searchTerm := "love" // 基本的なチェック fmt.Printf("Contains '%s'? %t\n", searchTerm, strings.Contains(text, searchTerm)) fmt.Printf("Has prefix ' Go'? %t\n", strings.HasPrefix(text, " Go")) fmt.Printf("Has suffix 'Go '? %t\n", strings.HasSuffix(text, "Go ")) // インデックス参照 fmt.Printf("Index of 'love': %d\n", strings.Index(text, searchTerm)) // 置換 newText := strings.Replace(text, "Go", "Python", 1) // 最初の出現を置換 fmt.Println("Replaced (first):", newText) allReplacedText := strings.ReplaceAll(text, "Go", "Rust") // すべての出現を置換 fmt.Println("Replaced (all):", allReplacedText) // トリミング trimmedText := strings.TrimSpace(text) fmt.Println("Trimmed:", trimmedText) trimmedPrefix := strings.TrimPrefix(text, " Go") fmt.Println("Trimmed prefix:", trimmedPrefix) // 大文字小文字の変換 fmt.Println("Uppercase:", strings.ToUpper(trimmedText)) fmt.Println("Lowercase:", strings.ToLower(trimmedText)) // 分割と結合 sentence := "apple,banana,orange" fruits := strings.Split(sentence, ",") fmt.Println("Split fruits:", fruits) joinedFruits := strings.Join(fruits, " and ") fmt.Println("Joined fruits:", joinedFruits) }
6. strconv
:文字列変換
The strconv
package provides functions for converting between strings and basic data types like integers, floating-point numbers, and booleans. It's essential when interacting with user input, configuration files, or external systems that communicate with string representations of data.
主な関数:
strconv.Atoi()
: 文字列を整数に変換します。strconv.Itoa()
: 整数を文字列に変換します。strconv.ParseInt()
: 指定された基数とビットサイズで文字列を整数に解析します。strconv.ParseFloat()
: 文字列を浮動小数点数に解析します。strconv.ParseBool()
: 文字列をブール値に解析します。strconv.FormatInt()
,strconv.FormatFloat()
,strconv.FormatBool()
: 基本型を文字列にフォーマットします。
例:
package main import ( "fmt" "strconv" ) func main() { // 文字列から整数へ strInt := "123" numInt, err := strconv.Atoi(strInt) if err != nil { fmt.Println("Error converting string to int:", err) } else { fmt.Printf("String '%s' to int: %d (type: %T)\n", strInt, numInt, numInt) } // 整数から文字列へ intVal := 456 strVal := strconv.Itoa(intVal) fmt.Printf("Int %d to string: '%s' (type: %T)\n", intVal, strVal, strVal) // 文字列から浮動小数点数へ strFloat := "3.14159" numFloat, err := strconv.ParseFloat(strFloat, 64) // 64 は float64、32 は float32 if err != nil { fmt.Println("Error converting string to float:", err) } else { fmt.Printf("String '%s' to float: %f (type: %T)\n", strFloat, numFloat, numFloat) } // 浮動小数点数から文字列へ floatVal := 2.71828 strFloatVal := strconv.FormatFloat(floatVal, 'f', 4, 64) // 'f' は10進数、小数点以下4桁、float64 fmt.Printf("Float %f to string: '%s' (type: %T)\n", floatVal, strFloatVal, strFloatVal) // 文字列からブール値へ strBoolTrue := "true" boolTrue, err := strconv.ParseBool(strBoolTrue) if err != nil { fmt.Println("Error converting 'true' to bool:", err) } else { fmt.Printf("String '%s' to bool: %t (type: %T)\n", strBoolTrue, boolTrue, boolTrue) } strBoolFalse := "0" // "0", "f", "F", "false", "FALSE", "False" は false として解析されます boolFalse, err := strconv.ParseBool(strBoolFalse) if err != nil { fmt.Println("Error converting '0' to bool:", err) } else { fmt.Printf("String '%s' to bool: %t (type: %T)\n", strBoolFalse, boolFalse, boolFalse) } // ブール値から文字列へ boolVal := true strBoolVal := strconv.FormatBool(boolVal) fmt.Printf("Bool %t to string: '%s' (type: %T)\n", boolVal, strBoolVal, strBoolVal) // 特定の基数での整数の解析 hexStr := "FF" hexVal, err := strconv.ParseInt(hexStr, 16, 8) // 基数16、8ビット整数 if err != nil { fmt.Println("Error parsing hex:", err) } else { fmt.Printf("Hex string '%s' (base 16) to int8: %d (type: %T)\n", hexStr, hexVal, hexVal) } }
結論
The fmt
, os
, io
, time
, strings
, and strconv
packages represent a fundamental toolkit for Go developers. Mastering their functionalities allows you to efficiently handle formatted output, interact with the operating system, manage data streams, work with dates and times, manipulate strings, and convert data types. By leveraging these core standard library components, you can write robust, readable, and idiomatic Go programs for a wide range of applications. As you delve deeper into Go, you'll discover how these packages are often the building blocks for more complex and specialized tasks.