構文基礎

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, float640
string""
boolfalse
pointer, slice, map, channel, interfacenil

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
)

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, false

Type 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+ サポート

基本構文

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==!= 演算子えんざんし比較ひかくできるかた

  1. 数値型すうちがたint, int8, int16, int32, int64, uint…、float32, float64complex64, complex128
  2. string
  3. bool
  4. すべてのポインタかた
  5. channel
  6. interface
  7. Struct:すべてのフィールドが comparable かた場合ばあいのみ
  8. Array要素ようそかたcomparable かた場合ばあいのみ

comparable でない型

  1. Slice
  2. Map
  3. Function
  4. 上記じょうき比較ひかく不可能ふかのうかたのフィールドをふく構造体こうぞうたい
// 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)

関連トピック