Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Contextとはなにか
Search
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
chiroruxx
June 17, 2026
Programming
140
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Contextとはなにか
2026/06/17 GoConnect #14 で登壇した資料です。
なお、登壇中にサンプルコードⅡforループが抜けていることが発覚しています。
chiroruxx
June 17, 2026
More Decks by chiroruxx
See All by chiroruxx
初心者エンジニアから中級者エンジニアになるためにオススメの1冊
chiroruxx
0
120
Laravelのパッケージ全部紹介する
chiroruxx
2
130
Gopher のための「自由な話し合い」ワークショップ
chiroruxx
0
43
PHPをGoで動かす
chiroruxx
0
96
Goを使ってTDDを体験しよう!
chiroruxx
1
1.1k
今ならできる!PhpStormプラグイン開発
chiroruxx
0
100
Go Connectへの想い
chiroruxx
0
210
eBPF with PHPをさわる
chiroruxx
0
180
sl完全に理解したつもり
chiroruxx
0
170
Other Decks in Programming
See All in Programming
コンテキストの使い捨てをやめる — ビジネスルール駆動開発と miko —
ioki
0
180
代数的データ型って何が嬉しいの? #frontend_phpcon_do
kajitack
8
3.3k
AIとASP.NET Coreで雑Webアプリを作った話
mayuki
0
460
Why Laravel apps break—Mastering the fundamentals to keep them maintainable
kentaroutakeda
1
340
プロパティの順序で型推論が壊れる!? TypeScript6.0の修正からContext-Sensitivityの仕組みを追う
bicstone
2
1.3k
LLM本来の能力を解き放つサンドボックス技術とAI民主化への適用
yukukotani
3
3.4k
Inside Stream API
skrb
1
660
Webフレームワークの ベンチマークについて
yusukebe
0
150
Lessons from Spec-Driven Development
simas
PRO
0
150
net-httpのHTTP/2対応について
naruse
0
460
TAKTでAI駆動開発の品質を設計する
j5ik2o
6
1.1k
ローカルLLMを使ってB2Bサービスを作っていての学び
yaotti
0
150
Featured
See All Featured
Testing 201, or: Great Expectations
jmmastey
46
8.2k
Large-scale JavaScript Application Architecture
addyosmani
515
110k
The Organizational Zoo: Understanding Human Behavior Agility Through Metaphoric Constructive Conversations (based on the works of Arthur Shelley, Ph.D)
kimpetersen
PRO
0
360
Design and Strategy: How to Deal with People Who Don’t "Get" Design
morganepeng
133
19k
Lightning Talk: Beautiful Slides for Beginners
inesmontani
PRO
2
570
Sharpening the Axe: The Primacy of Toolmaking
bcantrill
46
2.9k
End of SEO as We Know It (SMX Advanced Version)
ipullrank
3
4.2k
Beyond borders and beyond the search box: How to win the global "messy middle" with AI-driven SEO
davidcarrasco
3
150
Faster Mobile Websites
deanohume
310
31k
Leading Effective Engineering Teams in the AI Era
addyosmani
9
2k
Groundhog Day: Seeking Process in Gaming for Health
codingconduct
0
200
Visual Storytelling: How to be a Superhuman Communicator
reverentgeek
2
550
Transcript
Contextとはなにか 2026/06/17 GoConnect #14
⾃⼰紹介 ちひろ X: @chiroruxxxx 株式会社モリサワ
俺はContextがわからん Goの話ね
みんな知ってる Context // GetUser はユーザを返す func (s *UserService) GetUser( ctx
context.Context, id uint, ) (*User, error) { return s.repository.FindByID(ctx, id) } 引数で受け取って 引数にわたす Contextって一体なんなんだ!?
公式によると “A Context carries a deadline, a cancellation signal,
and other values across API boundaries. ” コンテキストは、期限、キャンセルシグナル、およびその他の値 をAPI境界を越えて伝達します。 なるほどわからん
先に結論 自分なりに解釈すると 「ゴルーチンを使う場面において 親ゴルーチンの情報を子ゴルーチンに伝えるための デザインパターンの実装」 props に似てるね!
それはチャネルでは? まず、基本的な話から
ゴルーチン間の データのやりとり 呼び出し時にデータを引数で渡す パッケージ変数を使う チャネルを経由して渡す
呼び出し時に データを引数で 渡す conn, err := listener.Accept() for { if
err != nil { log.Print(err) continue } go handleConn(conn) }
パッケージ変数 を使う package bank import "sync" var ( mu sync.Mutex
balance int ) // Balance は残高を取得する func Balance() int { mu.Lock() defer mu.Unlock() return balance } // Deposit は預金する func Deposit(amount int) { mu.Lock() defer mu.Unlock() balance += amount }
チャネル 入れた順に取り出せる データが無い場合は入るまで待つ select で複数のチャネルから取り出せる 閉じるとゼロ値を取り出す
何回取ってもゼロ値が返る
キャンセル あるゴルーチンが他ゴルーチンを止める方法は無い main関数はプロセス自体が終了するので別 他のゴルーチンを止めるには、チャネルで状態を管理して キャンセル状態を知らせる キャンセルするときにチャネルを閉じる(ブロードキャスト)
そのチャネルからゼロ値を取得できたらキャンセル
チャネルを経由 して渡す // pooling は1秒ごとにファイルに変更がないかチェックする func pooling(done chan struct{}) error
{ cache, err := getFile() if err != nil { return err } tick := time.Tick(1 * time.Second) select { case <-done: fmt.Println("cancelled") return nil case <-tick: f, err := getFile() if err != nil { return err } if !f.equals(cache) { fmt.Println("file is changed!") break } } return nil }
チャネルを経由 して渡す done = make(chan struct{}) go func() { err
:= pooling(done) if err != nil { log.Print(err) } }() // ...do something close(done)
Contextと チャネル キャンセルも含めた様々な状態を一括で伝搬できるようにした のがContext Contextによって何かができるようになるのではなく キレイに実装するためのただのデザインパターン Contextの実体はチャネルだと言っても過言ではない
Contextの 実装
Contextの 使い⽅ // pooling は1秒ごとにファイルに変更がないかチェックする func pooling(ctx context.Context) error {
cache, err := getFile() if err != nil { return err } tick := time.Tick(1 * time.Second) select { case <-ctx.Done(): fmt.Println("cancelled") return nil case <-tick: f, err := getFile() if err != nil { return err } if !f.equals(cache) { fmt.Println("file is changed!") break } } return nil }
Contextの 使い⽅ ctx := context.Background() ctx, cancel := context.WithCancel(ctx) go
func() { err := pooling(ctx) if err != nil { log.Print(err) } }() // ...do something cancel()
歴史的経緯 Context は Sameer Ajmani氏による “Go Concurrency Patterns: Context”が元
Go サーバにおいて ハンドラはリクエスト固有の値にアクセスする必要があるが いつリクエストを完了、タイムアウト、キャンセルさせるべきか? このデザインパターンが golang.org/x/net/context に入る Go サーバの話だったので net パッケージ 標準化された context パッケージになった
再掲: みんな知ってる Context // GetUser はユーザを返す func (s *UserService) GetUser(
ctx context.Context, id uint, ) (*User, error) { return s.repository.FindByID(ctx, id) } 引数で受け取って 引数にわたす
ユーザーランド app router library auth0 db sendgrid みんなが書いてる コード ゴルーチン
処理 ゴルーチン 処理
まとめ 公式: コンテキストは、期限、キャンセルシグナル、およびその他 の値をAPI境界を越えて伝達します。 自分の解釈: Contextは「ゴルーチンを使う場面において 親ゴルーチンの情報を子ゴルーチンに伝えるための デザインパターンの実装」
自分の言葉に置き換えて説明ができると、理解しやすい
参考⽂献 いくつかのコードは 丸善出版『プログラミング言語Go』 アラ ン・ドノバン、ブライアン・カーニハン著 から引用しました。