Upgrade to Pro — share decks privately, control downloads, hide ads and more …

empty struct

Avatar for tesso tesso
November 18, 2024
60

empty struct

https://gijutsu-club.connpass.com/event/334645/presentation/

#2 学生と社会人LTでの発表資料

Avatar for tesso

tesso

November 18, 2024

Transcript

  1. @tesso57 @tesso57 (てっそ) - 修士1年 - 研究 : 暗号理論 -

    ナンバーナイン 開発アルバイト - go, connect-go - FPSゲーマー - valorant - deadlock - 漫画好き
  2. @tesso57 今日のお話 func unique(list []string) []string { uniqueMap := make(map[string]bool)

    for _, entry := range list { if _, value := uniqueMap[entry]; !value { uniqueMap[entry] = true } } return slices.Collect(maps.Keys(uniqueMap)) }
  3. @tesso57 今日のお話 func unique(list []string) []string { uniqueMap := make(map[string]bool)

    for _, entry := range list { if _, value := uniqueMap[entry]; !value { uniqueMap[entry] = true } } return slices.Collect(maps.Keys(uniqueMap)) } func unique(list []string) []string { uniqueMap := make(map[string]struct{}) for _, entry := range list { if _, value := uniqueMap[entry]; !value { uniqueMap[entry] = struct{}{} } } return slices.Collect(maps.Keys(uniqueMap)) }
  4. @tesso57 struct{}について • 構造体 • フィールドを持たない構造体 • メモリを消費しない(0 byte) •

    同じアドレスを参照する x := 0 y := struct{}{} fmt.Println(unsafe.Sizeof(x)) // 8 fmt.Println(unsafe.Sizeof(y)) // 0 var a, b struct{} fmt.Printf("%p\n", &a) // 0x1046f07a0 fmt.Printf("%p\n", &b) // 0x1046f07a0
  5. @tesso57 struct{}のユースケース : unique // 配列のuniqueを取る関数 func unique(list []string) []string

    { uniqueMap := make(map[string]struct{}) // マップを作成 for _, entry := range list { if _, value := uniqueMap[entry]; !value { // 値が存在しない場合,マップに追加 uniqueMap[entry] = struct{}{} } } return slices.Collect(maps.Keys(uniqueMap)) // スライスに変換 }
  6. @tesso57 struct{}のユースケース : 通知 done := make(chan struct{}) // チャンネルの作成

    go func() { // 並列処理 time.Sleep(time.Second) // 1秒待つ done <- struct{}{} // チャンネルに空の構造体を送信 }() <-done // 受信を待つ fmt.Println("done")
  7. @tesso57 struct{}のユースケース : 存在確認 type encodeState struct { bytes.Buffer ptrLevel

    uint ptrSeen map[any]struct{} } func (me mapEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) { if e.ptrLevel++; e.ptrLevel > startDetectingCyclesAfter { ptr := v.UnsafePointer() if _, ok := e.ptrSeen[ptr]; ok { e.error(&UnsupportedValueError{ v, fmt.Sprintf("encountered a cycle via %s", v.Type())}) } e.ptrSeen[ptr] = struct{}{} defer delete(e.ptrSeen, ptr) } https://cs.opensource.google/go/go/+/master:src/encoding/json/encode.go;l=274;bpv=0;bpt=1
  8. @tesso57 struct{}の仕組み var zerobase uintptr … //go:linkname mallocgc func mallocgc(size

    uintptr, typ *_type, needzero bool) unsafe.Pointer { … if size == 0 { return unsafe.Pointer(&zerobase) } https://go.dev/src/runtime/malloc.go