LoginSignup
0
1

More than 3 years have passed since last update.

Golang context.Value() でKey周りを調べた にゃ

Last updated at Posted at 2020-02-25

context.WithValue() の Key はどうなのか調べた奴
メンバーに変数がないときは気をつけよう・・・・ 構造体を切り替えればオケ

(Qiitaに書くようなレベルなのだろうか・・・)

サンプルコード

ctx.go
package main

import "context"

type (
    plainKey struct{}
    empty    struct{}
    key      struct{ s string }
    value    struct{ s string }
)

var (
    key1  = key{s: "k1"}
    key2  = key{s: "k2"}
    pKey1 = plainKey{}
    pKey2 = plainKey{}
    ekey  = empty{}
)

func main() {

    v1 := value{s: "one"}
    v2 := value{s: "two"}
    v3 := value{s: "three"}
    v4 := value{s: "four"}

    ctx := context.Background()

    ctx = context.WithValue(ctx, key1, v1)
    ctx = context.WithValue(ctx, key2, v2)
    println("Key1:", ctx.Value(key1).(value).s)
    println("Key2:", ctx.Value(key2).(value).s)

    ctx = context.WithValue(ctx, &key1, v3)
    ctx = context.WithValue(ctx, &key2, v4)
    println("Key3:", ctx.Value(&key1).(value).s)
    println("Key4:", ctx.Value(&key2).(value).s)

    v5 := value{s: "five"}
    v6 := value{s: "six"}

    ctx = context.WithValue(ctx, pKey1, v1)
    ctx = context.WithValue(ctx, pKey2, v2)
    ctx = context.WithValue(ctx, ekey, v5)
    println("pKey1:", ctx.Value(pKey1).(value).s)
    println("pKey2:", ctx.Value(pKey2).(value).s)
    println("ekey5:", ctx.Value(ekey).(value).s)

    ctx = context.WithValue(ctx, &pKey1, v3)
    ctx = context.WithValue(ctx, &pKey2, v4)
    ctx = context.WithValue(ctx, ekey, v6)
    println("pKey3:", ctx.Value(&pKey1).(value).s)
    println("pKey4:", ctx.Value(&pKey2).(value).s)
    println("ekey6:", ctx.Value(ekey).(value).s)
}

実行

go run ctx.go 
Key1: one
Key2: two
Key3: three
Key4: four
pKey1: two
pKey2: two
ekey5: five
pKey3: four
pKey4: four
ekey6: six
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1