Skip to content

Instantly share code, notes, and snippets.

@atsushi-kitazawa
Last active February 14, 2021 16:25
Show Gist options
  • Save atsushi-kitazawa/266e24a58715d46831cfb26b63f13434 to your computer and use it in GitHub Desktop.
Save atsushi-kitazawa/266e24a58715d46831cfb26b63f13434 to your computer and use it in GitHub Desktop.
go programing note

Hello World

package main

import "fmt"

func main() {
  fmt.Println("hello world.")
}

変数宣言

var i int = 10
var s string = "aaa"
var b bool = false
var f float64 = 10.5

// 暗黙宣言も可
a := "hoge"

// 定数宣言
const c = 100

ポインタ

func pointerTest() {
        var var1 int = 10
        // ポインタ変数の宣言 * をつける。& でアドレスを参照する。
        var var2 *int = &var1
        fmt.Println(var1)
        // アドレスが表示される
        fmt.Println(var2)
        // アドレスが指す値が表示される
        fmt.Println(*var2)

        pointerTest2(var2)
}

// ポインタ変数を引数に取る関数の宣言
func pointerTest2(i *int) {
        fmt.Println(i)
        fmt.Println(*i)
}

// 構造体のポインタ変数を引数に取る関数の宣言
func pointerTest3(p *Person) {
        // &{1 hoge {hoge@example.com}}
        fmt.Println(p)
        // 0xc000072180
        fmt.Printf("%p\n", p)
        // {1 hoge {hoge@example.com}} 
        fmt.Println(*p)
}

func main() {
        var hoge *Person = &person
        pointerTest3(hoge)
}

関数宣言

func add(x int, y int) (int) {
  reutn x + y
}

  • 変数の型チェック
fmt.Println("v is of type %T\n", v)

構造体

// 宣言
 type Person struct {
   id    int
   name  string
   email Email
 }
 
 type Email struct {
   address string
 }
 
// 初期化
hoge := Person{1, "hoge", Email{"hoge@example.com"}}
uga := Person{id: 1, name: "uga", email: Email{"uga@example.com"}}
 
// 初期化関数用意
func NewPerson(id int, name string, email string) *Person {
        person := new(Person)
        person.id = id
        person.name = name
        person.email = Email{email}
        return person
}
// 関数を利用して初期化
var ahe *Person = NewPerson(3, "ahe", "ahe@example.com")

制御文

// for
for i := 0; i < 10; i++ {
  // something
}

// if
if s == "foo" {
  // something
} else if s == "bar" {
  // something
} else {
  // something
}

// switch
switch s {
  case "a":
    // something...
  case "b":
    // something...
  default:
    // something...
}

文字列

// 複数行の文字列の宣言
s := `aaa
  bbb
  ccc`

// string <-> []byte
s := string(buf)
b := []byte(s)

// 空かどうかの判定
1) if len(s) > 0
2) if s != ""

// 文字列連結

マップ、スライス、チャネル

// map
func mapTest() {
          // 宣言
          m := map[string]string{"key1": "value1", "key2": "value2", "key3": "value3"}
          // Printに渡す 「map=map[key1:value1 key2:value2 key3:value3]」
          fmt.Printf("map=%s\n", m)
          // キーで値にアクセス
          fmt.Printf("map[key1]=%s\n", m["key1"])
          fmt.Printf("map[key2]=%s\n", m["key2"])
          fmt.Printf("map[key3]=%s\n", m["key3"])
          // forで全要素にアクセス
          for k, v := range m {
          fmt.Println(k + ":" + v)
        }
}

// slice
// 部分取得(文字列でも利用可)
// Slice[start:end] : start から end - 1 まで
// Slice[start:]    : start から最後尾まで
// Slice[:end]      : 先頭から end - 1 まで
// Slice[:]         : 先頭から最後尾まで

// map の slice
var mapSlice []map[string]string
mapSlice = []map[string]string{{"key1": "value1", "key2": "value2"}, {"key3": "value3", "key4": "value4"}}
fmt.Println(mapSlice) // 「[map[key1:value1 key2:value2] map[key3:value3 key4:value4]]」

// channel

ファイル操作

// file open
file, err := os.Open("aaa.txt")

// file create 
file, err := os.Create("aaa.txt")

// mkdir
err := os.MkdirAll(dir, 0777)

// get dir of path
filepath,Dir(path) // when path is [aaa/bbb/test.html], return [aaa/bbb]

Testコード

package <test target package name>

import (
  "testing"
)

func TestMain(m *testing.M) {
  // before process
  
  code := m.Run()
  
  // after process
  
  os.Exit(code)
}

func TestAbc(t *testing.T) {
  result := Abc()
  
  assert.Equal(t, result, "aaa")
}

TIPS

  • パッケージ関連でエラーが発生したら「go mod tidy」で幸せになれるかもしれない
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment