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
380
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
これからAgentCoreを触る方へトレンドはGatewayです
har1101
6
440
ADKを使って簡単にAIエージェントを作ってみよう
k1mu21
0
280
エンジニア向け会社紹介/Findy Company Profile
findyinc
6
360k
キャリア迷子上等 ─ "ない道"は自分で作ればいい
16bitidol
3
2.5k
スマートグラスで並列バイブコーディング
hyshu
0
270
過去最大のMCPアップデート! 2026-07-28 RC版の謎に迫る
licux
6
430
肥大化するレガシーコードに立ち向かうためのインターフェース分離と依存の逆転 / JJUG CCC 2026 Spring
hirokunimaeta
0
650
技術的負債解消で開発者の未来を開く- AIの力でコード刷新
kmd2kmd
0
120
Inside Stream API
skrb
1
810
OS アップデート対応の取り組み方がもっと共有されてほしい
andpad
0
110
ローカルLLMでどこまでコードが書けるか -縮小版 / How much code can be written on a local LLM Shortened
kishida
2
140
1B+ /day規模のログを管理する技術
broadleaf
0
120
Featured
See All Featured
The Power of CSS Pseudo Elements
geoffreycrofte
82
6.3k
Understanding Cognitive Biases in Performance Measurement
bluesmoon
32
2.9k
Why Our Code Smells
bkeepers
PRO
340
58k
Templates, Plugins, & Blocks: Oh My! Creating the theme that thinks of everything
marktimemedia
31
2.8k
Money Talks: Using Revenue to Get Sh*t Done
nikkihalliwell
0
270
Code Reviewing Like a Champion
maltzj
528
40k
Dominate Local Search Results - an insider guide to GBP, reviews, and Local SEO
greggifford
PRO
0
200
How to build a perfect <img>
jonoalderson
1
5.8k
Visualizing Your Data: Incorporating Mongo into Loggly Infrastructure
mongodb
49
10k
GraphQLとの向き合い方2022年版
quramy
50
15k
Primal Persuasion: How to Engage the Brain for Learning That Lasts
tmiket
0
380
SEO for Brand Visibility & Recognition
aleyda
0
4.6k
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』 アラ ン・ドノバン、ブライアン・カーニハン著 から引用しました。