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
410
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
50
PHPをGoで動かす
chiroruxx
0
110
Goを使ってTDDを体験しよう!
chiroruxx
1
1.1k
今ならできる!PhpStormプラグイン開発
chiroruxx
0
120
Go Connectへの想い
chiroruxx
0
230
eBPF with PHPをさわる
chiroruxx
0
190
sl完全に理解したつもり
chiroruxx
0
180
Other Decks in Programming
See All in Programming
JAWS-UG横浜 #102 AWSサ終供養LT会 成仏できない AWS サービスたち 〜本日、三体供養します〜
maroon1st
0
240
Apache Hive: そしてCloud Native Lakehouseへ
okumin
1
170
PHP初心者セッション2026 〜生成AIでは見えない裏側を知る:今だからLAMPを通して仕組みを学ぶ〜
kashioka
0
660
「正の参照」と 「負の導出」で組む ハーネスエンジニアリング
cottpan
1
150
壊れたパーサから始める関数型設計と構成的なパーサ #fp_matsuri
raiga0310
2
400
『コードを書く以外の』エンジニアリング〜課金基盤移行プロジェクト推進のためのTips4選
yuriko1211
0
540
SLOをサービス品質の共通言語にするために 取り組んできたこと
wakana0222
0
550
吝嗇家のためのAI活用 / AI development for miser - ChatGPT + Issue Driven Development
tooppoo
0
200
Embedded SREと共に達成した会員管理システムのAWS移行 - SRE NEXT 2026 ランチスポンサーセッション
niftycorp
PRO
1
3k
The Past, Present, and Future of Enterprise Java
ivargrimstad
0
390
SREの積み重ねがAI駆動開発のガードレールになった ― 7つの実践/SRE Guardrails The 7
tomoyakitaura
8
5.4k
エンジニアにデザインハーネスを 〜デザインプロセスを規定するためのハーネス〜 / Design harness from an engineer's perspective
rkaga
2
1.7k
Featured
See All Featured
Future Trends and Review - Lecture 12 - Web Technologies (1019888BNR)
signer
PRO
0
3.6k
The Curse of the Amulet
leimatthew05
2
13k
Writing Fast Ruby
sferik
630
63k
Understanding Cognitive Biases in Performance Measurement
bluesmoon
32
3k
[RailsConf 2023] Rails as a piece of cake
palkan
59
6.8k
The World Runs on Bad Software
bkeepers
PRO
72
12k
Test your architecture with Archunit
thirion
1
2.3k
How to Grow Your eCommerce with AI & Automation
katarinadahlin
PRO
1
230
The browser strikes back
jonoalderson
0
1.4k
Joys of Absence: A Defence of Solitary Play
codingconduct
1
420
The Psychology of Web Performance [Beyond Tellerrand 2023]
tammyeverts
49
3.5k
Leo the Paperboy
mayatellez
8
1.9k
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』 アラ ン・ドノバン、ブライアン・カーニハン著 から引用しました。