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
·
SiteGround - Reliable hosting with speed, security, and support you can count on.
→
chiroruxx
June 17, 2026
Programming
210
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
44
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
These Five Tricks Can Make Your Apps Greener, Cheaper, & Nicer
hollycummins
0
280
JJUG CCC 2026 Spring: JSpecify で実現する Kotlin フレンドリーな Java API 設計
ternbusty
1
150
ローカルLLMを使ってB2Bサービスを作っていての学び
yaotti
0
150
Why Laravel apps break—Mastering the fundamentals to keep them maintainable
kentaroutakeda
1
340
Old Dog, New Tricks: The Java 25 Reinvention - JNation
bazlur_rahman
0
150
「AIで開発し、AIを届ける」をEvalでつなぐ 〜AIネイティブに始めるプロダクト開発の実践〜 / Connecting "Develop with AI, deliver AI" with Eval
rkaga
4
4.8k
過去最大のMCPアップデート! 2026-07-28 RC版の謎に迫る
licux
6
200
Swiftのレキシカルスコープ管理
kntkymt
0
220
気づいたらRubyで100作品 ー クリエイティブコーディングが生活の一部になるまで / 100 Ruby Sketches Later: How Creative Coding Became Part of My Life
chobishiba
3
560
軽量Java基盤の設計 DIコンテナに頼らない、長期保守と1秒起動の実現 JJUG CCC 2026 Spring
macha64
0
480
Vue × Nuxt × Oxc どこまで使える?実運用の現在地
andpad
0
120
作って学ぶ、 JSX (TSX) ランタイムの基本
syumai
7
1.6k
Featured
See All Featured
世界の人気アプリ100個を分析して見えたペイウォール設計の心得
akihiro_kokubo
PRO
71
40k
[RailsConf 2023 Opening Keynote] The Magic of Rails
eileencodes
31
10k
Optimizing for Happiness
mojombo
378
71k
Self-Hosted WebAssembly Runtime for Runtime-Neutral Checkpoint/Restore in Edge–Cloud Continuum
chikuwait
0
580
Taking LLMs out of the black box: A practical guide to human-in-the-loop distillation
inesmontani
PRO
3
2.3k
Exploring anti-patterns in Rails
aemeredith
3
400
Ecommerce SEO: The Keys for Success Now & Beyond - #SERPConf2024
aleyda
1
2k
Producing Creativity
orderedlist
PRO
348
40k
Scaling GitHub
holman
464
140k
Evolution of real-time – Irina Nazarova, EuRuKo, 2024
irinanazarova
9
1.4k
The SEO Collaboration Effect
kristinabergwall1
1
480
Bootstrapping a Software Product
garrettdimon
PRO
307
120k
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』 アラ ン・ドノバン、ブライアン・カーニハン著 から引用しました。