フラミナル

考え方や調べたことを書き殴ります。IT技術系記事多め

go reference を眺めて知らないことまとめておく

go.dev を読んで個人的に知ったことをまとめる

raw string

fmt.Println(`aaa
aa

aaa
`)

iota

const (
    c0 = iota  // c0 == 0
    c1 = iota  // c1 == 1
    c2 = iota  // c2 == 2
)

const (
    a = 1 << iota  // a == 1  (iota == 0)
    b = 1 << iota  // b == 2  (iota == 1)
    c = 3          // c == 3  (iota == 2, unused)
    d = 1 << iota  // d == 8  (iota == 3)
)

const (
    u         = iota * 42  // u == 0     (untyped integer constant)
    v float64 = iota * 42  // v == 42.0  (float64 constant)
    w         = iota * 42  // w == 84    (untyped integer constant)
)

const x = iota  // x == 0
const y = iota  // y == 0

map / slice の初期化状態

p1 := &[]int{}    // p1 points to an initialized, empty slice with value []int{} and length 0
p2 := new([]int)  // p2 points to an uninitialized slice with value nil and length 0

なので、len()でチェックした方が良い。

メソッドの呼び出し方

package main
import "fmt"

type test struct {a int}

func main() {
    var t test

    t.test1()
    t.test2()

    // これでもいける
    test.test1(t)
    (test).test1(t)
}

func (t test) test1() {fmt.Println(t.a)}
func (t *test) test2() {fmt.Println(t.a)}

slice

package main

import "fmt"

func main() {
    a := [5]int{1, 2, 3, 4, 5}

    // index 1 ~ 3 [2 3 4]
    fmt.Println(a[1:4])

    // index 1 ~ [2 3 4 5]
    fmt.Println(a[1:])

    // index ~ 1 [1 2]
    fmt.Println(a[:2])

    // index ~ [1 2 3 4 5]
    fmt.Println(a[:])

    // index 0 ~ 3 [1 2] (cap を減らせる)
    fmt.Println(a[0:2:4])

    fmt.Println(a[1:3])
    fmt.Println(cap(a[1:3])) // 4
    fmt.Println(a[1:3:3])
    fmt.Println(cap(a[1:3:3])) // 2
}

演算子

引用

package main

import "fmt"

func main() {
    a, b := 255, 85 // 2進数では、11111111, 01010101

    // 論理積
    fmt.Printf("%08b\n", a&b) // 01010101

    // 論理和
    fmt.Printf("%08b\n", a|b) // 11111111

    //排他的論理和
    fmt.Printf("%08b\n", a^b) // 10101010

    // 論理積の否定
    fmt.Printf("%08b\n", a&^b) // 10101010

    //算術シフト
    c, d := 15, 240            // 00001111, 11110000
    fmt.Printf("%08b\n", c<<4) // 11110000
    fmt.Printf("%08b\n", d>>4) // 00001111
}

go言語 演算子

copy method

var a = [...]int{0, 1, 2, 3, 4, 5, 6, 7}
var s = make([]int, 6)
var b = make([]byte, 5)
n1 := copy(s, a[0:])            // n1 == 6, s == []int{0, 1, 2, 3, 4, 5}
n2 := copy(s, s[2:])            // n2 == 4, s == []int{2, 3, 4, 5, 4, 5}
n3 := copy(b, "Hello, World!")  // n3 == 5, b == []byte("Hello")