構文基礎
Go 言語の基本構文:変数、定数、型。
Hello World
package main
import "fmt"
func main() {
fmt.Println("Hello World")
}Variables
宣言方法
// 完全な宣言
var name string = "Alice"
// 型推論
var age = 25
// 短縮宣言(関数内のみ)
count := 10
// 複数変数の宣言
var (
x int = 1
y string = "hello"
z bool = true
)
// 同時代入
a, b := 1, 2ゼロ値
初期化されていない変数にはゼロ値がある:
| 型 | ゼロ値 |
|---|---|
int, float64 | 0 |
string | "" |
bool | false |
pointer, slice, map, channel, interface | nil |
Constants
定数の宣言と使用。
const Pi = 3.14159
const (
StatusOK = 200
StatusError = 500
)iota
自動増加する定数ジェネレータ。
const (
Sunday = iota // 0
Monday // 1
Tuesday // 2
Wednesday // 3
Thursday // 4
Friday // 5
Saturday // 6
)iota の高度な使用法
// ビットマスク
const (
Read = 1 << iota // 1
Write // 2
Execute // 4
)
// 値をスキップ
const (
A = iota // 0
_ // 1 をスキップ
B // 2
)
// データサイズ
const (
_ = iota
KB = 1 << (10 * iota) // 1024
MB // 1048576
GB // 1073741824
)- Links
Base64 Encoding
Go は標準 Base64 エンコーディングと URL セーフエンコーディングをサポート。
import "encoding/base64"
data := "Hello, World!"
// 標準エンコーディング
encoded := base64.StdEncoding.EncodeToString([]byte(data))
// SGVsbG8sIFdvcmxkIQ==
decoded, _ := base64.StdEncoding.DecodeString(encoded)
// Hello, World!
// URL セーフエンコーディング
urlEncoded := base64.URLEncoding.EncodeToString([]byte(data))Type Assertions
型アサーションは interface{} から具体的な型を取得するために使用。
var i interface{} = "hello"
// 基本的なアサーション(失敗すると panic)
s := i.(string)
fmt.Println(s) // "hello"
// 安全なアサーション
s, ok := i.(string)
if ok {
fmt.Println(s)
}
// 誤ったアサーション
n, ok := i.(int)
fmt.Println(n, ok) // 0, falseType Switch
func describe(i interface{}) {
switch v := i.(type) {
case int:
fmt.Printf("Integer: %d\n", v)
case string:
fmt.Printf("String: %s\n", v)
case bool:
fmt.Printf("Boolean: %t\n", v)
default:
fmt.Printf("Unknown type: %T\n", v)
}
}Generics
Go 1.18+ サポート
- Resource: All your comparable types
- Links:
基本構文
func Min[T int | float64](a, b T) T {
if a < b {
return a
}
return b
}
// 使用
Min[int](1, 2) // 1
Min(1.5, 2.5) // 1.5(型推論)comparable 型
comparable は == と != 演算子で比較できる型:
- 数値型:
int,int8,int16,int32,int64,uint…、float32,float64、complex64,complex128 stringbool- すべてのポインタ型
channelinterfaceStruct:すべてのフィールドがcomparable型の場合のみArray:要素型がcomparable型の場合のみ
comparable でない型
- Slice
- Map
- Function
- 上記の比較不可能な型のフィールドを含む構造体
// map key として使用可能
map[string]int // OK
map[*string]int // OK
map[[]string]int // コンパイルエラー、slice は comparable でないGo Files
go.mod:モジュール定義go.sum:依存関係の検証(hashで一貫性を確保)go.work:ワークスペース設定
JSON
Decoding & Encoding
import "encoding/json"
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
// Marshal (struct → JSON)
p := Person{Name: "Alice", Age: 30}
data, _ := json.Marshal(p)
// {"name":"Alice","age":30}
// Unmarshal (JSON → struct)
var p2 Person
json.Unmarshal([]byte(`{"name":"Bob","age":25}`), &p2)omitempty
-:フィールドを常に除外
フィールドが空の値(false, 0, nil pointer, nil interface, 空の array/slice/map/string)の場合、エンコーディングから省略することを指定。
type Person struct {
Name string `json:"name,omitempty"`
Age int `json:"age,omitempty"`
Address string `json:"-"` // JSON に含まれない
}Time
- Time Format:
"2006-01-02 15:04:05.999999999 -0700 MST"
import "time"
now := time.Now()
// フォーマット
formatted := now.Format("2006-01-02 15:04:05")
// パース
t, _ := time.Parse("2006-01-02", "2024-01-15")
// 時間の演算
tomorrow := now.Add(24 * time.Hour)
duration := tomorrow.Sub(now)- Links: Time Practice