Goを書くときの個人用メモ


よく参照する公式ドキュメント

Package fmt
- fmt.Printf()で出力する時に型に応じて、表記方法が違うため確認したり

Testの事前処理

test.go
//テストの事前処理を書く
func TestMain(m *testing.M) {
    println("before all...")

    code := m.Run()

    println("after all...")

    os.Exit(code)
}

構造体の宣言いろいろ

Go言語(golang) 構造体の定義と使い方

test.go

func TestValidation(t *testing.T) {

    t.Run("テストケース", func(t *testing.T) {
        // structを定義及び代入、スライスにする
        test_case := []struct {
            from    string
            to      string
            expected error
        }{
            {"20200101", "20200102", nil},
            {"20200101", "20191229", errors.New(fmt.Sprintf("date from(%s) is not before than to (%s).", "20200529", "20200601"))},
        }
        for _, v := range test_case {
            actual := Validation(v.from, v.to)
            if actual != v.expected {
                if actual != nil {
                     // error同士だと比較できないので(error).Error()->stringで比較する
                    if actual.Error() != v.expected.Error() {
                        t.Errorf("There is unexpected result: actual(%s), expected(%s) startdate(%s) endDate(%s)", actual, v.expected, v.from, v.to)
                    }
                } else {
                    t.Errorf("There is unexpected result: actual(%s), expected(%s) startdate(%s) endDate(%s)", actual, v.expected, v.from, v.to)
                }
            }

        }

    })

}


index.go
f, err := os.Create("write.txt")
if err != nil {
    fmt.Println("cannot open the file")
}
 defer f.Close()
 defer func(){
    err := f.Close()
    if err != nil {
        fmt.Println(err)
    }
 }

// 以下write処理等を書く