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
chiroruxx
June 17, 2026
Programming
390
1
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
130
Laravelのパッケージ全部紹介する
chiroruxx
2
140
Gopher のための「自由な話し合い」ワークショップ
chiroruxx
0
48
PHPをGoで動かす
chiroruxx
0
100
Goを使ってTDDを体験しよう!
chiroruxx
1
1.1k
今ならできる!PhpStormプラグイン開発
chiroruxx
0
110
Go Connectへの想い
chiroruxx
0
220
eBPF with PHPをさわる
chiroruxx
0
190
sl完全に理解したつもり
chiroruxx
0
180
Other Decks in Programming
See All in Programming
正しくソフトウェアを作る、前提を疑うための認知の視点 / doubt-premise
minodriven
21
7.2k
jQueryをバージョンアップする前に使いたいjQuery Migrate
matsuo_atsushi
0
620
決定論的オーケストレーションの設計と実装 / Design and Implementation of Deterministic Orchestration
nrslib
4
1.6k
フロントエンドとバックエンドで「1文字」を揃えよう
youkidearitai
PRO
0
780
SLOをサービス品質の共通言語にするために 取り組んできたこと
wakana0222
0
250
スマートグラスで並列バイブコーディング
hyshu
0
270
IBM Bobを活用したレガシーアプリの最新化
oniak3ibm
PRO
1
230
OS アップデート対応の取り組み方がもっと共有されてほしい
andpad
0
110
ランチタイムLT会3周年!ランチタイムLT会を3年間続けられたお話
y0hgi
1
120
これからAgentCoreを触る方へトレンドはGatewayです
har1101
6
450
【やさしく解説 設計編 #0】DDDのコード、読めるのに分からない人へ
panda728
PRO
0
120
SREの積み重ねがAI駆動開発のガードレールになった ― 7つの実践/SRE Guardrails The 7
tomoyakitaura
1
180
Featured
See All Featured
Leading Effective Engineering Teams in the AI Era
addyosmani
9
2.1k
Navigating Algorithm Shifts & AI Overviews - #SMXNext
aleyda
1
1.3k
Beyond borders and beyond the search box: How to win the global "messy middle" with AI-driven SEO
davidcarrasco
3
170
Accessibility Awareness
sabderemane
1
150
The Myth of the Modular Monolith - Day 2 Keynote - Rails World 2024
eileencodes
28
3.5k
The SEO identity crisis: Don't let AI make you average
varn
0
510
Avoiding the “Bad Training, Faster” Trap in the Age of AI
tmiket
0
190
Building Applications with DynamoDB
mza
96
7.1k
Stop Working from a Prison Cell
hatefulcrawdad
274
21k
Color Theory Basics | Prateek | Gurzu
gurzu
0
380
CSS Pre-Processors: Stylus, Less & Sass
bermonpainter
360
30k
What the history of the web can teach us about the future of AI
inesmontani
PRO
1
630
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』 アラ ン・ドノバン、ブライアン・カーニハン著 から引用しました。