<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Nobuo Miura's Notes]]></title><description><![CDATA[Welcome to Nobuo Miura's Notes!
This is my little corner of the internet where I share personal projects, open-source software, everyday discoveries, ideas, and]]></description><link>https://nobuo-miura.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 21:46:02 GMT</lastBuildDate><atom:link href="https://nobuo-miura.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Clessidra 1.3.0: Siri, Reminders, and a New Widget]]></title><description><![CDATA[Clessidra 1.3.0 adds Siri and Shortcuts support, Spotlight search, new reminders, and a yearly countdown widget. Submitted for App Store review.]]></description><link>https://nobuo-miura.hashnode.dev/clessidra-1-3-0-siri-shortcuts-reminders</link><guid isPermaLink="true">https://nobuo-miura.hashnode.dev/clessidra-1-3-0-siri-shortcuts-reminders</guid><category><![CDATA[iOS]]></category><category><![CDATA[Swift]]></category><category><![CDATA[Changelog]]></category><dc:creator><![CDATA[Nobuo Miura]]></dc:creator><pubDate>Sun, 29 Nov 2026 12:40:55 GMT</pubDate><content:encoded><![CDATA[<p>English | <a href="https://nobuo-miura.hashnode.dev/clessidra-1-3-0-siri-shortcuts-reminders-ja">日本語</a></p>
<p>I’ve submitted Clessidra 1.3.0 for App Store review.</p>
<p>Clessidra is my iPhone and iPad app for visualizing your time and keeping a bucket list. You enter your birthday and choose a lifespan as a personal reference point, then organize the things you want to do with deadlines, priorities, and smaller steps.</p>
<p>This update makes it easier to capture an idea when it comes to mind and come back to it later.</p>
<h2>Add ideas with Siri and Shortcuts</h2>
<p>Version 1.3.0 adds support for Siri and the Shortcuts app.</p>
<p>You can add a bucket list item without opening Clessidra, check your remaining time, or ask which items have the nearest deadlines. In the Shortcuts app, you can also specify a category and a deadline by age or date when adding an item.</p>
<p>There’s also a new “Add to Bucket List” control for Control Center and the Lock Screen. Tapping it opens Clessidra directly to the add screen.</p>
<p>If an idea comes to mind while you’re doing something else, these give you a few more ways to save it.</p>
<h2>Find your bucket list in Spotlight</h2>
<p>You’ll be able to search for bucket list items by title or category in Spotlight and tap a result to open its details.</p>
<p>Completed items appear in search results too, so you can find something you’ve already done as well as something you’re still planning.</p>
<h2>Two new reminders</h2>
<p>Clessidra already supports reminders for individual deadlines. This update adds two more ways to revisit your plans.</p>
<p><strong>Before your birthday</strong></p>
<p>If you have unfinished items with an age deadline such as “by age 40,” Clessidra can remind you before that birthday and tell you how many are left.</p>
<p>You can choose one week, one month, or three months in advance. If there are no matching unfinished items, there’s no reminder.</p>
<p><strong>This Week’s Step</strong></p>
<p>A weekly reminder picks one unfinished item from your bucket list and brings it back to your attention.</p>
<p>You choose the day and time. Items that haven’t been featured recently are picked first, giving you a chance to revisit plans you may have forgotten about.</p>
<p>Both reminders are off by default and can be enabled under Notifications in Settings. Weekly reminders are scheduled four weeks ahead and refreshed when you open the app or change your items.</p>
<h2>A view of this year</h2>
<p>The new This Year widget shows how many days remain in the year and how much of the year has passed. It also shows the number of unfinished bucket list items due this year.</p>
<p>It’s available for the Home Screen and Lock Screen, and works even before you’ve entered your birthday.</p>
<p>A year gives you a shorter timeframe to think about: what would you like to do before the next one begins?</p>
<h2>Duplicate an item</h2>
<p>You can now duplicate a bucket list item and edit it before saving it as a new entry.</p>
<p>The copy keeps details such as notes, category, and steps, while resetting completion status and step progress. For something you’d like to do again, you can reuse the plan you already made.</p>
<h2>Availability</h2>
<p>Version 1.3.0 is currently awaiting App Store review. The features described here will be available once the update is released.</p>
<p>Clessidra is available for iPhone and iPad. All features are free, with optional tips to support development.</p>
<p><a href="https://apps.apple.com/app/id6820957009">Clessidra on the App Store</a> · <a href="https://nobuo-miura.dev/en/apps/clessidra/">About Clessidra</a></p>
]]></content:encoded></item><item><title><![CDATA[Clessidra 1.3.0：Siri・通知・新しいウィジェット]]></title><description><![CDATA[人生の残り時間とやりたいことを管理するiOSアプリ「Clessidra」。審査提出中のv1.3.0で追加するSiri・ショートカット対応、Spotlight検索、2種類の通知、今年の残り日数ウィジェットを紹介します。]]></description><link>https://nobuo-miura.hashnode.dev/clessidra-1-3-0-siri-shortcuts-reminders-ja</link><guid isPermaLink="true">https://nobuo-miura.hashnode.dev/clessidra-1-3-0-siri-shortcuts-reminders-ja</guid><category><![CDATA[iOS]]></category><category><![CDATA[app development]]></category><category><![CDATA[Productivity]]></category><category><![CDATA[Changelog]]></category><dc:creator><![CDATA[Nobuo Miura]]></dc:creator><pubDate>Sun, 29 Nov 2026 12:39:13 GMT</pubDate><content:encoded><![CDATA[<p><a href="https://nobuo-miura.hashnode.dev/clessidra-1-3-0-siri-shortcuts-reminders">English</a> | 日本語</p>
<p>Clessidra 1.3.0をApp Storeの審査に提出しました。</p>
<p>Clessidraは、残りの時間を可視化し、人生でやりたいことを管理するiPhone・iPadアプリです。誕生日と、自分の目安として使う想定寿命を入力し、やりたいことに期限や優先度を付けたり、小さなステップに分けたりできます。</p>
<p>今回の更新では、思いついたことをその場で残し、あとから見返しやすくしました。</p>
<h2>Siri・ショートカットから追加</h2>
<p>v1.3.0では、Siriとショートカットアプリに対応します。</p>
<p>Clessidraを開かずにやりたいことを追加したり、残り時間や期限が近い項目を確認したりできます。ショートカットアプリでは、追加する項目のカテゴリや、年齢・日付による期限も指定できます。</p>
<p>コントロールセンターとロック画面に置ける「やりたいことを追加」のコントロールも追加しました。タップすると、Clessidraの追加画面が開きます。</p>
<p>何かをしている途中で思いついたときにも、残しておく方法が増えます。</p>
<h2>Spotlightから検索</h2>
<p>Spotlightで、やりたいことをタイトルやカテゴリから検索できるようになります。検索結果をタップすると、その項目の詳細が開きます。</p>
<p>達成済みの項目も検索対象なので、これからの予定だけでなく、以前に叶えたことも探せます。</p>
<h2>2種類の通知を追加</h2>
<p>Clessidraには、項目ごとの期限を知らせる通知があります。今回は、予定を見返すための通知を2種類追加しました。</p>
<p><strong>誕生日の前に知らせる通知</strong></p>
<p>「40歳まで」のように年齢で期限を設定した項目が未達成で残っていると、その誕生日の前に件数を知らせます。</p>
<p>通知のタイミングは、1週間前・1ヶ月前・3ヶ月前から選べます。該当する未達成の項目がなければ通知しません。</p>
<p><strong>今週の一歩</strong></p>
<p>週に1回、未達成のやりたいことを1つ選んで知らせます。</p>
<p>曜日と時刻は自分で設定できます。しばらく取り上げていない項目を優先して選ぶので、忘れかけていた予定を見返すきっかけにもなります。</p>
<p>どちらの通知も初期状態ではオフで、設定の「通知」から有効にできます。週に1回の通知は4週間分を先に登録し、アプリを開いたときや項目を変更したときに更新します。</p>
<h2>今年の残り時間を表示</h2>
<p>新しい「今年」ウィジェットでは、今年の残り日数と経過率を表示します。今年中が期限の、未達成のやりたいことの件数も確認できます。</p>
<p>ホーム画面とロック画面に対応し、誕生日を設定する前でも使えます。</p>
<p>1年という少し短い区切りで、次の年を迎えるまでに何をしたいか考えられます。</p>
<h2>やりたいことを複製</h2>
<p>やりたいことを複製し、編集してから新しい項目として保存できるようになります。</p>
<p>メモ・カテゴリ・ステップなどは引き継ぎ、達成状態とステップの進み具合はリセットします。またやりたいことがあれば、以前に作った計画を使って準備できます。</p>
<h2>配信について</h2>
<p>v1.3.0は現在、App Storeの審査待ちです。この記事で紹介した新機能は、アップデートの配信後に使えるようになります。</p>
<p>ClessidraはiPhone・iPadに対応しています。すべての機能を無料で利用できます。</p>
<p><a href="https://apps.apple.com/app/id6820957009">App StoreでClessidraを見る</a> · <a href="https://nobuo-miura.dev/ja/apps/clessidra/">Clessidraについて</a></p>
]]></content:encoded></item><item><title><![CDATA[Hic Fui 1.3.0: A New Way to Look Back at Your Visits]]></title><description><![CDATA[Preview Hic Fui 1.3.0: yearly and monthly visit summaries, On This Day reminders, and shareable trip maps. Currently awaiting App Store review.]]></description><link>https://nobuo-miura.hashnode.dev/hic-fui-1-3-0-visit-summaries-trip-maps</link><guid isPermaLink="true">https://nobuo-miura.hashnode.dev/hic-fui-1-3-0-visit-summaries-trip-maps</guid><category><![CDATA[iOS]]></category><category><![CDATA[Swift]]></category><category><![CDATA[Mobile Development]]></category><category><![CDATA[Travel]]></category><dc:creator><![CDATA[Nobuo Miura]]></dc:creator><pubDate>Sun, 29 Nov 2026 12:34:41 GMT</pubDate><content:encoded><![CDATA[<p>English | <a href="https://nobuo-miura.hashnode.dev/hic-fui-1-3-0">日本語</a></p>
<p>I’ve submitted Hic Fui 1.3.0 for App Store review.</p>
<p>Hic Fui is my app for keeping a personal record of the places you visit. Its name means “I was here” in Latin. You can check in somewhere, add a past visit, or organize your visits into trips.</p>
<p>This update adds more ways to look back at those records: yearly and monthly summaries, “On This Day” notifications, and trip maps you can share as images.</p>
<h2>Your year—or month—in places</h2>
<p>The new <strong>Year in Review</strong> and <strong>Month in Review</strong> bring your visits together in one view.</p>
<p>Choose a year or month in Stats to see the countries and places you visited, your total visits, and the countries and places you visited for the first time during that period. You can also see your most visited place and the trips associated with that period.</p>
<p>The summary includes a world map highlighting the countries you visited. You can turn it into an image in either a portrait Story format or a square format.</p>
<p>Place names are hidden in the image by default. If you want to include your most visited place, you can turn them on before sharing.</p>
<h2>A reminder of where you were</h2>
<p>“On This Day” already shows visits from the same date in previous years at the top of your history.</p>
<p>In 1.3.0, you can also enable notifications and choose a time in Settings. When you have a visit to remember, Hic Fui can remind you without needing to open the app first.</p>
<p>A café from last year or a stop on a trip several years ago can be easy to forget until something brings it back. This gives those records another chance to be seen.</p>
<p>The reminders use local notifications scheduled on your device.</p>
<h2>Trip maps with a color for each day</h2>
<p>Trip routes now use a different color for each day, making it easier to follow a trip across several days.</p>
<p>Long connections, such as those between cities on a flight, appear as dotted arcs. The map connects the places you recorded in visit order; it doesn’t track your movement between them.</p>
<p>You can also export a trip’s map and summary as an image. Like the yearly and monthly summaries, trip images support portrait and square formats, with an option to include place names.</p>
<h2>Easier changes to a trip</h2>
<p>You can now select visits you’ve already recorded and add them directly from the trip screen.</p>
<p>This is useful when you logged places as you went and want to organize them into a trip afterward. Adding all visits within a trip’s dates is still available, while individual selection gives you more control over which visits belong.</p>
<p>To remove a visit from a trip, swipe its row. The visit stays in your history.</p>
<h2>A clearer confirmation when merging places</h2>
<p>Hic Fui uses each place’s time zone to display visit dates and calculate yearly statistics.</p>
<p>When two places have different time zones, merging them can change the displayed date—or even the year—of some visits. Version 1.3.0 makes that effect clearer before you confirm: the merge screen shows how many visits would change date or year, along with an example.</p>
<h2>Availability</h2>
<p>Hic Fui is available for iPhone and iPad running iOS 26 or later. All features are free, with optional tips to support development.</p>
<p>Your records are stored on your devices and in your own iCloud. Sharing a summary is something you choose to do by exporting an image.</p>
<p><strong>Version 1.3.0 is currently awaiting App Store review.</strong> The features described above will be available once the update is approved and released.</p>
<p><a href="https://apps.apple.com/app/id6824098359">Hic Fui on the App Store</a></p>
<img src="https://cdn.hashnode.com/uploads/covers/6b08111d4979c1f0ace19cc8/66db1075-2353-4425-a48f-4ff5b560822b.png" alt="" style="display:block;margin:0 auto" />]]></content:encoded></item><item><title><![CDATA[Hic Fui 1.3.0 — 旅の記録を振り返って、共有する]]></title><description><![CDATA[訪れた場所を記録するiOSアプリ「Hic Fui」1.3.0を審査に提出しました。年間・月間まとめや旅行の地図を画像で共有する機能、「過去の今日」の通知、旅行への訪問追加など、今回の変更を紹介します。]]></description><link>https://nobuo-miura.hashnode.dev/hic-fui-1-3-0</link><guid isPermaLink="true">https://nobuo-miura.hashnode.dev/hic-fui-1-3-0</guid><category><![CDATA[iOS]]></category><category><![CDATA[Mobile Development]]></category><category><![CDATA[Changelog]]></category><category><![CDATA[mobile app development]]></category><dc:creator><![CDATA[Nobuo Miura]]></dc:creator><pubDate>Sun, 29 Nov 2026 12:24:01 GMT</pubDate><content:encoded><![CDATA[<p><a href="https://nobuo-miura.hashnode.dev/hic-fui-1-3-0-visit-summaries-trip-maps">English</a> | 日本語</p>
<p>Hic Fui 1.3.0 を審査に提出しました。</p>
<p>今回のアップデートでは、共有機能を中心に、旅行の記録や振り返りに役立つ機能を追加しました。</p>
<ul>
<li><strong>年間・月間のまとめ</strong><br />統計画面で年や月を選ぶと、その期間に訪れた国や場所をまとめて見られるようになりました。まとめは画像にして共有できます。</li>
<li><strong>「過去の今日」の通知</strong><br />過去の今日に訪れた場所を、通知でお知らせできるようになりました。設定からオンにして、通知を受け取る時刻を選べます。</li>
<li><strong>旅行の地図の表示と共有</strong><br />地図上の経路を日ごとに色分けし、飛行機などでの長距離移動は点線で表示するようにしました。旅行の地図と概要を画像にして共有することもできます。</li>
<li><strong>記録済みの訪問を旅行に追加</strong><br />旅行の画面から、記録済みの訪問を選んで追加できるようになりました。旅行から外すときは、訪問の行をスワイプします。</li>
<li><strong>場所をまとめる際の確認</strong><br />場所をまとめることで訪問の日付や年が変わる場合に、確認画面で対象の件数と例を表示するようにしました。</li>
</ul>
<p><a href="https://apps.apple.com/app/id6824098359">Hic Fui on the App Store</a></p>
<img src="https://cdn.hashnode.com/uploads/covers/6b08111d4979c1f0ace19cc8/e6ea620b-2779-4375-a93f-a3d5d8332b17.png" alt="" style="display:block;margin:0 auto" />]]></content:encoded></item><item><title><![CDATA[GitHub UI Translator v0.2.0 リリース]]></title><description><![CDATA[GitHub UI Translator v0.2.0でユーザ辞書を追加。GitHubの翻訳を好みやチームの用語に合わせて変更できます。Alt／Option＋クリックでの編集や、辞書のエクスポート・インポート機能を紹介します。]]></description><link>https://nobuo-miura.hashnode.dev/github-ui-translator-v0-2-0</link><guid isPermaLink="true">https://nobuo-miura.hashnode.dev/github-ui-translator-v0-2-0</guid><category><![CDATA[OSS]]></category><category><![CDATA[Browser Extension]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[translation]]></category><category><![CDATA[localization]]></category><dc:creator><![CDATA[Nobuo Miura]]></dc:creator><pubDate>Sat, 28 Nov 2026 04:11:49 GMT</pubDate><content:encoded><![CDATA[<p>GitHub UI Translator v0.2.0 をリリースしました。</p>
<p>今回のアップデートでは「ユーザ辞書」機能を追加しました。同梱されている訳を、自分に馴染みのある表現に変更できます。</p>
<img src="https://cdn.hashnode.com/uploads/covers/6b08111d4979c1f0ace19cc8/d8be8d2a-6772-463b-b0e7-708176f4a5d0.png" alt="" style="display:block;margin:0 auto" />

<p>たとえば「Pull request」。人やプロジェクトによっては、「PR」「MR」「マージリクエスト」の方がしっくりくるかもしれません。また、日本語に訳すよりも、原文の英語のままの方がわかりやすい言葉もあると思います。</p>
<p>ユーザ辞書では、こうした好みに合わせて表示を調整できます。</p>
<p>気になる語を <strong>Alt＋クリック（MacではOption＋クリック）</strong> してその場で、自分が使いたい表現に変更できます。</p>
<img src="https://cdn.hashnode.com/uploads/covers/6b08111d4979c1f0ace19cc8/cf5f0baa-bb5a-42ff-a00a-763f603eb04c.png" alt="" style="display:block;margin:0 auto" />

<p>個人の好みだけでなく、企業やプロジェクト内で決まっている用語に揃えたい場合にも使えます。普段使っている呼び方に合わせることで、GitHubの画面も読みやすくなると思います。</p>
<p>ユーザ辞書はエクスポート・インポートにも対応しています。自分で作った辞書を別の環境に移したり、チームで共有して初期設定として使ったりすることもできます。</p>
<p>訳が気になっていた言葉や、いつもの呼び方に変えたい言葉があれば、ぜひユーザ辞書を使ってみてください。</p>
<hr />
<h2>GitHubを日本語化する「GitHub UI Translator」</h2>
<p>GitHub UI Translatorは、GitHubのメニューやボタンなどのUIを、日本語を含む複数の言語に翻訳するブラウザー拡張機能です。Chrome・Edge・Firefoxに対応しています。</p>
<p>翻訳はブラウザー内の辞書を使って行うため、外部の翻訳APIは使用しません。READMEやイシュー、コメント、コードなどのユーザーが書いた内容は翻訳対象から除外しています。</p>
<p>GitHubの英語表示を日本語にしたい方や、普段使っている用語に合わせて画面の表示を調整したい方に使っていただけるとうれしいです。</p>
<p>インストール方法や詳しい使い方は、<a href="https://nobuo-miura.dev/ja/oss/github-ui-translator/">GitHub UI Translatorの公式ドキュメント</a>をご覧ください。</p>
<hr />
]]></content:encoded></item><item><title><![CDATA[Rust Cheat Sheet]]></title><description><![CDATA[Rust 1.98 and Edition 2024 cheat sheet with examples of ownership, borrowing, lifetimes, traits, error handling, concurrency, testing, and Cargo.]]></description><link>https://nobuo-miura.hashnode.dev/rust-cheat-sheet</link><guid isPermaLink="true">https://nobuo-miura.hashnode.dev/rust-cheat-sheet</guid><category><![CDATA[Rust]]></category><category><![CDATA[rust lang]]></category><category><![CDATA[cheatsheet]]></category><dc:creator><![CDATA[Nobuo Miura]]></dc:creator><pubDate>Fri, 27 Nov 2026 10:38:15 GMT</pubDate><content:encoded><![CDATA[<p>This cheat sheet is based on Rust 1.98 and the Rust 2024 Edition.</p>
<hr />
<h2>Installation and updates</h2>
<p><a href="https://rust-lang.org/tools/install/">Official Rust installation guide</a></p>
<p>The recommended way to manage a Rust toolchain is with the official <code>rustup</code> tool. On macOS, Linux, WSL, and other Unix-like systems, run the command published on the official website and follow the prompts:</p>
<pre><code class="language-bash">curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
</code></pre>
<p>On Windows, download and run <code>rustup-init.exe</code> from the <a href="https://rust-lang.org/tools/install/">official installation page</a>. Depending on your environment, you may also need the Visual Studio C++ Build Tools.</p>
<p>Restart your terminal after installation, then check the installed versions:</p>
<pre><code class="language-bash">rustc --version
cargo --version
rustup --version
</code></pre>
<p>Update the stable toolchain and install the formatter and linter with:</p>
<pre><code class="language-bash">rustup update stable
rustup component add rustfmt clippy
</code></pre>
<p>If an existing project contains <code>rust-toolchain.toml</code> or <code>rust-toolchain</code>, follow that project-level toolchain declaration. Libraries can declare their minimum supported Rust version (MSRV) with <code>rust-version</code> in <code>Cargo.toml</code>.</p>
<hr />
<h2>Program structure</h2>
<pre><code class="language-rust">fn main() {
    println!("Hello, Rust 1.98!");
}
</code></pre>
<ul>
<li>An executable starts at the <code>main</code> function.</li>
<li>Statements usually end with <code>;</code>.</li>
<li>A name ending in <code>!</code>, such as <code>println!</code>, is a macro invocation.</li>
</ul>
<h3>Comments</h3>
<table>
<thead>
<tr>
<th>Syntax</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td><code>// ...</code></td>
<td>Regular comment through the end of the line</td>
</tr>
<tr>
<td><code>/* ... */</code></td>
<td>Regular block comment; block comments can be nested</td>
</tr>
<tr>
<td><code>/// ...</code>, <code>/** ... */</code></td>
<td>Outer documentation comment for the following item</td>
</tr>
<tr>
<td><code>//! ...</code>, <code>/*! ... */</code></td>
<td>Inner documentation comment for the containing crate or module</td>
</tr>
</tbody></table>
<pre><code class="language-rust">// A line comment
let value = 42;

/* A block comment can
   span multiple lines. */
assert_eq!(value, 42);
</code></pre>
<p>Documentation comments are parsed as Markdown and included in the API documentation generated by <code>cargo doc</code>. Their code blocks are normally run as documentation tests by <code>cargo test</code>.</p>
<pre><code class="language-rust">mod math {
    //! Basic arithmetic helpers.

    /// Adds two integers.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(2 + 3, 5);
    /// ```
    pub fn add(left: i32, right: i32) -&gt; i32 {
        left + right
    }
}

assert_eq!(math::add(2, 3), 5);
</code></pre>
<p>Create and run a Cargo project with:</p>
<pre><code class="language-bash">cargo new hello-rust
cd hello-rust
cargo run
</code></pre>
<p>New Cargo projects use <code>edition = "2024"</code> in <code>Cargo.toml</code>.</p>
<h3>Keywords</h3>
<p><a href="https://doc.rust-lang.org/reference/keywords.html">The Rust Reference: Keywords</a></p>
<p>Rust divides keywords into strict keywords, reserved keywords kept for future language features, and weak keywords that are special only in specific contexts.</p>
<h4>Strict keywords</h4>
<table>
<thead>
<tr>
<th>Keyword</th>
<th>Primary use</th>
</tr>
</thead>
<tbody><tr>
<td><code>_</code></td>
<td>Ignore a value in a pattern, or ask the compiler to infer a type or value</td>
</tr>
<tr>
<td><code>as</code></td>
<td>Primitive casts, aliases in <code>use</code>, and qualified paths</td>
</tr>
<tr>
<td><code>async</code></td>
<td>Define a function, block, or closure that produces a <code>Future</code></td>
</tr>
<tr>
<td><code>await</code></td>
<td>Suspend the current async computation until a <code>Future</code> is ready</td>
</tr>
<tr>
<td><code>break</code></td>
<td>Exit a loop, optionally returning a value</td>
</tr>
<tr>
<td><code>const</code></td>
<td>Declare compile-time constants, const functions, blocks, or generics</td>
</tr>
<tr>
<td><code>continue</code></td>
<td>Skip the rest of the current loop iteration</td>
</tr>
<tr>
<td><code>crate</code></td>
<td>Refer to the current crate or its root</td>
</tr>
<tr>
<td><code>dyn</code></td>
<td>Form a dynamically dispatched trait object</td>
</tr>
<tr>
<td><code>else</code></td>
<td>Handle the branch where an <code>if</code> or <code>if let</code> condition does not match</td>
</tr>
<tr>
<td><code>enum</code></td>
<td>Define a type with multiple variants</td>
</tr>
<tr>
<td><code>extern</code></td>
<td>Work with external ABIs, functions, statics, or crates</td>
</tr>
<tr>
<td><code>false</code></td>
<td>The false <code>bool</code> literal</td>
</tr>
<tr>
<td><code>fn</code></td>
<td>Define a function or function-pointer type</td>
</tr>
<tr>
<td><code>for</code></td>
<td>Iterate over a value or implement a trait for a type</td>
</tr>
<tr>
<td><code>if</code></td>
<td>Branch on a Boolean condition</td>
</tr>
<tr>
<td><code>impl</code></td>
<td>Define inherent methods or implement a trait</td>
</tr>
<tr>
<td><code>in</code></td>
<td>Specify the value iterated by a <code>for</code> loop</td>
</tr>
<tr>
<td><code>let</code></td>
<td>Bind a value to a pattern</td>
</tr>
<tr>
<td><code>loop</code></td>
<td>Repeat until explicitly stopped</td>
</tr>
<tr>
<td><code>match</code></td>
<td>Perform exhaustive pattern matching</td>
</tr>
<tr>
<td><code>mod</code></td>
<td>Declare or define a module</td>
</tr>
<tr>
<td><code>move</code></td>
<td>Move captured values into a closure or async block</td>
</tr>
<tr>
<td><code>mut</code></td>
<td>Make a binding, reference, or pattern mutable</td>
</tr>
<tr>
<td><code>pub</code></td>
<td>Expose an item outside its default visibility boundary</td>
</tr>
<tr>
<td><code>ref</code></td>
<td>Bind by reference inside a pattern</td>
</tr>
<tr>
<td><code>return</code></td>
<td>Return from a function early</td>
</tr>
<tr>
<td><code>self</code></td>
<td>Refer to a method receiver or the current module</td>
</tr>
<tr>
<td><code>Self</code></td>
<td>Refer to the type currently being defined or implemented</td>
</tr>
<tr>
<td><code>static</code></td>
<td>Declare an item with a fixed storage location</td>
</tr>
<tr>
<td><code>struct</code></td>
<td>Define a named-field, tuple, or unit struct</td>
</tr>
<tr>
<td><code>super</code></td>
<td>Refer to the parent module</td>
</tr>
<tr>
<td><code>trait</code></td>
<td>Define shared behavior for types</td>
</tr>
<tr>
<td><code>true</code></td>
<td>The true <code>bool</code> literal</td>
</tr>
<tr>
<td><code>type</code></td>
<td>Define a type alias or associated type</td>
</tr>
<tr>
<td><code>unsafe</code></td>
<td>Mark operations or contracts the compiler cannot fully verify</td>
</tr>
<tr>
<td><code>use</code></td>
<td>Bring a path into scope or re-export an item</td>
</tr>
<tr>
<td><code>where</code></td>
<td>Write generic and lifetime bounds</td>
</tr>
<tr>
<td><code>while</code></td>
<td>Repeat while a Boolean condition remains true</td>
</tr>
</tbody></table>
<h4>Reserved keywords</h4>
<p><code>abstract</code>, <code>become</code>, <code>box</code>, <code>do</code>, <code>final</code>, <code>gen</code>, <code>macro</code>, <code>override</code>, <code>priv</code>, <code>try</code>, <code>typeof</code>, <code>unsized</code>, <code>virtual</code>, <code>yield</code></p>
<p>These are reserved for possible future language features. In Rust 1.98, they have no keyword behavior and cannot be used as ordinary identifiers. In particular, <code>typeof</code> is reserved but is not implemented as a type-inspection operator.</p>
<h4>Weak keywords</h4>
<table>
<thead>
<tr>
<th>Keyword</th>
<th>Context in which it is special</th>
</tr>
</thead>
<tbody><tr>
<td><code>'static</code></td>
<td>A lifetime valid for the entire program</td>
</tr>
<tr>
<td><code>macro_rules</code></td>
<td>Declare a declarative macro</td>
</tr>
<tr>
<td><code>raw</code></td>
<td>Create raw pointers with <code>&amp;raw const</code> or <code>&amp;raw mut</code></td>
</tr>
<tr>
<td><code>safe</code></td>
<td>Mark a function or static as safe inside an <code>unsafe extern</code> block</td>
</tr>
<tr>
<td><code>union</code></td>
<td>Define a type whose fields share storage</td>
</tr>
</tbody></table>
<p>When an identifier must match a keyword, a raw identifier such as <code>r#type</code> can be used where the grammar permits it.</p>
<hr />
<h2>Variables, constants, and primitive types</h2>
<h3>Variable declarations</h3>
<p>Bindings are immutable by default. Add <code>mut</code> when the value must change.</p>
<pre><code class="language-rust">let name = "Ferris";       // Inferred as &amp;str.
let age: u32 = 10;         // Explicit type.
let mut count = 0;         // Mutable binding.
count += 1;

// Destructure a value with a pattern.
let (x, y) = (10, 20);

// A declaration may omit its initializer if it is definitely initialized before use.
let status: String;
status = String::from("ready");
println!("{status}");
</code></pre>
<h3>Shadowing</h3>
<p><code>let</code> can declare a new binding with the same name. Unlike mutation, shadowing may also change the type.</p>
<pre><code class="language-rust">let spaces = "   ";
let spaces = spaces.len(); // &amp;str to usize
</code></pre>
<h3>Constants and statics</h3>
<pre><code class="language-rust">const MAX_RETRIES: u32 = 3;
static APPLICATION_NAME: &amp;str = "example";
</code></pre>
<ul>
<li>A <code>const</code> is evaluated at compile time and requires an explicit type.</li>
<li>A <code>static</code> has a fixed memory address for the duration of the program.</li>
<li>Accessing mutable <code>static mut</code> state requires <code>unsafe</code>; prefer synchronization primitives where appropriate.</li>
</ul>
<p>An atomic type works well for a simple counter shared across threads:</p>
<pre><code class="language-rust">use std::sync::atomic::{AtomicU64, Ordering};

static REQUEST_COUNT: AtomicU64 = AtomicU64::new(0);

fn next_request_count() -&gt; u64 {
    REQUEST_COUNT.fetch_add(1, Ordering::Relaxed) + 1
}

assert_eq!(next_request_count(), 1);
assert_eq!(next_request_count(), 2);
</code></pre>
<p><code>Relaxed</code> is appropriate here because only the atomicity of the counter matters; this counter does not synchronize the ordering of other memory accesses. Choose an ordering or a lock that matches the actual synchronization requirements.</p>
<h3>Values and literals</h3>
<p>Literals are values written directly in source code. Numeric literals may have a type suffix, and <code>_</code> can be used as a visual separator.</p>
<pre><code class="language-rust">let integer = 42;              // i32
let unsigned = 42_u64;         // u64
let floating = 3.14_f32;       // f32
let enabled = true;            // bool
let character = 'R';           // char
let text = "Rust";             // &amp;str
let byte = b'R';               // u8
let bytes = b"Rust";           // &amp;[u8; 4]
let raw = r#"A raw string does not escape \"#;
let million = 1_000_000;

assert_eq!(integer, 42);
assert_eq!(bytes, &amp;[82, 117, 115, 116]);
assert!(raw.contains('\\'));
assert_eq!(million, 1_000_000);
</code></pre>
<p>Values can also be produced by calls such as <code>String::from("Rust")</code> and by expressions such as <code>left + right</code>. Many Rust constructs are expressions: blocks, <code>if</code>, <code>match</code>, and <code>loop</code> can all produce values.</p>
<h3>Scalar types</h3>
<table>
<thead>
<tr>
<th>Category</th>
<th>Types</th>
<th>Notes</th>
</tr>
</thead>
<tbody><tr>
<td>Signed integers</td>
<td><code>i8</code>, <code>i16</code>, <code>i32</code>, <code>i64</code>, <code>i128</code>, <code>isize</code></td>
<td>Integer literals default to <code>i32</code></td>
</tr>
<tr>
<td>Unsigned integers</td>
<td><code>u8</code>, <code>u16</code>, <code>u32</code>, <code>u64</code>, <code>u128</code>, <code>usize</code></td>
<td><code>usize</code> is commonly used for sizes and indexes</td>
</tr>
<tr>
<td>Floating point</td>
<td><code>f32</code>, <code>f64</code></td>
<td>Defaults to <code>f64</code></td>
</tr>
<tr>
<td>Boolean</td>
<td><code>bool</code></td>
<td><code>true</code> or <code>false</code></td>
</tr>
<tr>
<td>Character</td>
<td><code>char</code></td>
<td>A four-byte Unicode scalar value</td>
</tr>
<tr>
<td>Unit</td>
<td><code>()</code></td>
<td>Represents the absence of another meaningful value</td>
</tr>
</tbody></table>
<pre><code class="language-rust">let decimal = 98_222;
let hex = 0xff;
let octal = 0o77;
let binary = 0b1111_0000;
let byte = b'A';
let ratio = 3.5_f64;
let enabled = true;
let crab = '🦀';
</code></pre>
<p>Debug builds detect integer overflow at runtime. Use explicit methods when wraparound or saturation is intentional.</p>
<pre><code class="language-rust">let value = u8::MAX;
assert_eq!(value.wrapping_add(1), 0);
assert_eq!(value.saturating_add(1), u8::MAX);
assert_eq!(value.checked_add(1), None);
</code></pre>
<h3>Compound types</h3>
<pre><code class="language-rust">// A tuple can contain values of different types.
let user = ("Ferris", 10, true);
let (name, age, active) = user;
println!("{name}: {age}, active={active}");

// An array has a fixed length that is part of its type.
let numbers: [i32; 3] = [10, 20, 30];
let zeros = [0; 5];
println!("{} {}", numbers[0], zeros.len());
</code></pre>
<p>Array indexing with <code>[]</code> panics when the index is out of bounds. Use <code>get</code> when absence is possible.</p>
<pre><code class="language-rust">let values = [10, 20, 30];
match values.get(5) {
    Some(value) =&gt; println!("{value}"),
    None =&gt; println!("out of bounds"),
}
</code></pre>
<h3>Type conversion</h3>
<p>Rust does not perform implicit numeric conversion. Use <code>as</code>, <code>From</code>, or <code>TryFrom</code> explicitly.</p>
<pre><code class="language-rust">let small: u8 = 42;
let large = u32::from(small); // Lossless conversion.

let integer = 42_i32;
let floating = integer as f64;
assert_eq!(floating, 42.0);

let value: i32 = 300;
let byte = u8::try_from(value); // Result&lt;u8, TryFromIntError&gt;
assert!(byte.is_err());

assert_eq!(char::from_u32(65), Some('A'));
</code></pre>
<p><code>as</code> can truncate a value. Prefer <code>TryFrom</code> when the input range is not guaranteed.</p>
<pre><code class="language-rust">let value = 300_u16;
assert_eq!(value as u8, 44);
assert!(u8::try_from(value).is_err());
</code></pre>
<h3>Type aliases and newtypes</h3>
<p>A type alias gives an existing type another name; it does not create a distinct type.</p>
<pre><code class="language-rust">type UserId = u64;
type IoResult&lt;T&gt; = Result&lt;T, std::io::Error&gt;;

fn load_user(id: UserId) -&gt; IoResult&lt;String&gt; {
    Ok(format!("user-{id}"))
}

let id: UserId = 42;
let raw_id: u64 = id;
assert_eq!(load_user(raw_id).unwrap(), "user-42");
</code></pre>
<p>Use the newtype pattern when values must not be mixed accidentally.</p>
<pre><code class="language-rust">struct UserId(u64);
struct ProductId(u64);

fn find_user(id: UserId) {
    println!("user={}", id.0);
}

find_user(UserId(42));
// find_user(ProductId(42)); // Different type: does not compile.
</code></pre>
<h3>Inspecting a type</h3>
<p>Rust has no built-in <code>typeof</code> operator. Use <code>std::any::type_name::&lt;T&gt;()</code> for a known type or <code>std::any::type_name_of_val</code> for a value.</p>
<pre><code class="language-rust">fn type_of&lt;T: ?Sized&gt;(_: &amp;T) -&gt; &amp;'static str {
    std::any::type_name::&lt;T&gt;()
}

let number = 123;
println!("{}", type_of(&amp;number));
println!("{}", std::any::type_name_of_val(&amp;number));
</code></pre>
<p>A helper that accepts its argument by value also works:</p>
<pre><code class="language-rust">fn type_of&lt;T&gt;(_: T) -&gt; &amp;'static str {
    std::any::type_name::&lt;T&gt;()
}

let number = 123;
println!("{}", type_of(number));
</code></pre>
<p>The by-value version moves non-<code>Copy</code> values such as <code>String</code>, so the borrowed form is usually more convenient. The exact output of <code>type_name</code> is not guaranteed and may change between compiler versions. Use it for diagnostics, not as a stable type identifier or application branching key.</p>
<h3>Operators</h3>
<table>
<thead>
<tr>
<th>Category</th>
<th>Operators</th>
<th>Notes</th>
</tr>
</thead>
<tbody><tr>
<td>Arithmetic</td>
<td><code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, <code>%</code></td>
<td>Integer division discards the fractional part</td>
</tr>
<tr>
<td>Unary</td>
<td><code>-</code>, <code>!</code></td>
<td>Numeric negation; Boolean negation or integer bitwise complement</td>
</tr>
<tr>
<td>Comparison</td>
<td><code>==</code>, <code>!=</code>, <code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, <code>&gt;=</code></td>
<td>Uses traits such as <code>PartialEq</code> and <code>PartialOrd</code></td>
</tr>
<tr>
<td>Logical</td>
<td><code>&amp;&amp;</code>, <code>||</code>, <code>!</code></td>
<td><code>&amp;&amp;</code> and <code>||</code> short-circuit</td>
</tr>
<tr>
<td>Bitwise</td>
<td><code>&amp;</code>, <code>|</code>, <code>^</code>, <code>&lt;&lt;</code>, <code>&gt;&gt;</code></td>
<td>Bit operations on integers</td>
</tr>
<tr>
<td>Assignment</td>
<td><code>=</code>, <code>+=</code>, <code>-=</code>, <code>*=</code>, <code>/=</code>, <code>%=</code>, <code>&amp;=</code>, <code>|=</code>, <code>^=</code>, <code>&lt;&lt;=</code>, <code>&gt;&gt;=</code></td>
<td>Includes compound assignment</td>
</tr>
<tr>
<td>Range</td>
<td><code>..</code>, <code>..=</code></td>
<td>Exclusive and inclusive upper bounds</td>
</tr>
<tr>
<td>Borrow and dereference</td>
<td><code>&amp;</code>, <code>&amp;mut</code>, <code>*</code></td>
<td>Create references and access their targets</td>
</tr>
<tr>
<td>Error propagation</td>
<td><code>?</code></td>
<td>Return early from <code>Result</code>, <code>Option</code>, and similar types</td>
</tr>
</tbody></table>
<pre><code class="language-rust">assert_eq!(7 / 2, 3);
assert_eq!(7.0 / 2.0, 3.5);
assert_eq!(-5_i32, 0 - 5);
assert_eq!(!true, false);

let mut value = 5;
value *= 2;
assert_eq!(value, 10);

let mut flags = 0b0011_u8;
flags |= 0b0100;
flags &lt;&lt;= 1;
assert_eq!(flags, 0b1110);

assert!((1..=10).contains(&amp;value));
</code></pre>
<p>User-defined types can support operators by implementing standard traits such as <code>Add</code>, <code>PartialEq</code>, and <code>Index</code>. Rust does not allow arbitrary new operators or custom operator precedence.</p>
<hr />
<h2>Ownership, borrowing, and slices</h2>
<p>Rust manages memory without a garbage collector by checking ownership rules at compile time.</p>
<h3>Ownership</h3>
<p>The three core rules are:</p>
<ol>
<li>Every value has an owner.</li>
<li>A value has only one owner at a time.</li>
<li>The value is dropped when its owner leaves scope.</li>
</ol>
<pre><code class="language-rust">let original = String::from("hello");
let moved = original; // Ownership moves to moved.

println!("{moved}");
// println!("{original}"); // Error: original was moved.
</code></pre>
<p>Types that implement <code>Copy</code>, such as <code>i32</code>, are copied on assignment.</p>
<pre><code class="language-rust">let x = 5;
let y = x;
println!("{x} {y}");
</code></pre>
<p>Use <code>clone</code> when an independent copy of heap-owned data is actually needed.</p>
<pre><code class="language-rust">let original = String::from("hello");
let cloned = original.clone();
println!("{original} {cloned}");
</code></pre>
<h3>Borrowing and references</h3>
<p>A reference borrows a value without taking ownership.</p>
<pre><code class="language-rust">fn length(text: &amp;str) -&gt; usize {
    text.len()
}

let message = String::from("hello");
let size = length(&amp;message);
println!("{message}: {size}");
</code></pre>
<p>The main borrowing rules are:</p>
<ul>
<li>Any number of shared references <code>&amp;T</code>, or one mutable reference <code>&amp;mut T</code>, may be active.</li>
<li>Shared and mutable references to the same value cannot be active at the same time.</li>
<li>A reference must always point to a valid value.</li>
</ul>
<pre><code class="language-rust">fn append_world(text: &amp;mut String) {
    text.push_str(", world");
}

let mut message = String::from("hello");
append_world(&amp;mut message);
println!("{message}");
</code></pre>
<h3>Slices</h3>
<p>A slice borrows a contiguous portion of a collection without owning the data.</p>
<pre><code class="language-rust">let numbers = [10, 20, 30, 40];
let middle: &amp;[i32] = &amp;numbers[1..3];
assert_eq!(middle, &amp;[20, 30]);

let text = String::from("hello world");
let hello: &amp;str = &amp;text[..5];
assert_eq!(hello, "hello");
</code></pre>
<p>String ranges must fall on UTF-8 character boundaries or they panic. Use <code>chars</code> for Unicode scalar values and <code>bytes</code> for bytes.</p>
<pre><code class="language-rust">let text = "日本語";
let characters: Vec&lt;char&gt; = text.chars().collect();
assert_eq!(characters, vec!['日', '本', '語']);
assert_eq!(text.len(), 9);          // UTF-8 bytes
assert_eq!(text.chars().count(), 3); // Unicode scalar values
</code></pre>
<h3>Lifetime overview</h3>
<p>Lifetimes describe how long references remain valid. The compiler infers them in most code.</p>
<pre><code class="language-rust">fn longest&lt;'a&gt;(x: &amp;'a str, y: &amp;'a str) -&gt; &amp;'a str {
    if x.len() &gt;= y.len() { x } else { y }
}
</code></pre>
<p><code>'a</code> says that the returned reference cannot outlive the shorter-lived input reference. It does not extend the lifetime of either value. A string literal has the <code>'static</code> lifetime because its data is available for the entire program.</p>
<hr />
<h2>Control flow</h2>
<h3><code>if</code>, <code>if let</code>, and <code>let else</code></h3>
<p><code>if</code> is an expression, so it can produce a value. Its condition must be a <code>bool</code>.</p>
<pre><code class="language-rust">let score = 80;
let grade = if score &gt;= 80 { "A" } else { "B" };

let name = Some("Ferris");
if let Some(value) = name {
    println!("{value}");
}

fn print_name(name: Option&lt;&amp;str&gt;) {
    let Some(name) = name else {
        println!("No name was provided");
        return;
    };
    println!("{name}");
}
</code></pre>
<h3><code>loop</code>, <code>while</code>, and <code>for</code></h3>
<pre><code class="language-rust">let mut count = 0;
let result = loop {
    count += 1;
    if count == 3 {
        break count * 10; // break can return a value from loop.
    }
};
assert_eq!(result, 30);

while count &gt; 0 {
    count -= 1;
}

for value in [10, 20, 30] {
    println!("{value}");
}

for number in 1..=5 {
    if number % 2 == 0 {
        continue;
    }
    println!("odd: {number}");
}
</code></pre>
<p><code>for</code> calls <code>into_iter</code>. Passing a collection by value may consume it.</p>
<pre><code class="language-rust">let mut names = vec![String::from("Alice"), String::from("Bob")];

for name in &amp;names {        // iter(): &amp;String
    println!("{name}");
}
for name in &amp;mut names {    // iter_mut(): &amp;mut String
    name.push('!');
}
assert_eq!(names, vec!["Alice!", "Bob!"]);

// for name in names { }    // into_iter(): String; consumes names.
</code></pre>
<h3>Loop labels</h3>
<pre><code class="language-rust">'outer: for x in 0..3 {
    for y in 0..3 {
        if x + y == 3 {
            break 'outer;
        }
    }
}
</code></pre>
<h3><code>match</code></h3>
<p><code>match</code> must cover every possible pattern.</p>
<pre><code class="language-rust">let number = 7;

let description = match number {
    0 =&gt; "zero",
    1..=9 =&gt; "one digit",
    n if n % 2 == 0 =&gt; "even",
    _ =&gt; "other",
};

println!("{description}");
</code></pre>
<pre><code class="language-rust">let point = (0, 5);
match point {
    (0, y) =&gt; println!("on the y-axis: {y}"),
    (x, 0) =&gt; println!("on the x-axis: {x}"),
    (x, y) =&gt; println!("({x}, {y})"),
}
</code></pre>
<hr />
<h2>Functions and closures</h2>
<p>Function parameter and return types are explicit. The final expression is returned when it has no semicolon.</p>
<pre><code class="language-rust">fn add(left: i32, right: i32) -&gt; i32 {
    left + right
}

fn divide(left: f64, right: f64) -&gt; Option&lt;f64&gt; {
    if right == 0.0 { return None; }
    Some(left / right)
}

let value = { let base = 10; base * 2 };
assert_eq!(value, 20);
</code></pre>
<p>Closures can borrow or capture values from their environment. Their types are usually inferred.</p>
<pre><code class="language-rust">let offset = 10;
let add_offset = |value: i32| value + offset;
assert_eq!(add_offset(5), 15);

let message = String::from("hello");
let show = move || println!("{message}");
show();
</code></pre>
<p>Closures implement <code>Fn</code>, <code>FnMut</code>, or <code>FnOnce</code> depending on how they use captured values.</p>
<pre><code class="language-rust">fn apply_twice&lt;F&gt;(mut operation: F, value: i32) -&gt; i32
where F: FnMut(i32) -&gt; i32,
{
    let once = operation(value);
    operation(once)
}
assert_eq!(apply_twice(|x| x + 1, 10), 12);
</code></pre>
<p>Functions and non-capturing closures can be used as <code>fn</code> pointers.</p>
<pre><code class="language-rust">fn double(value: i32) -&gt; i32 { value * 2 }
fn calculate(operation: fn(i32) -&gt; i32, value: i32) -&gt; i32 { operation(value) }
assert_eq!(calculate(double, 5), 10);
</code></pre>
<hr />
<h2>Structs, unions, enums, and patterns</h2>
<h3>Structs and methods</h3>
<pre><code class="language-rust">#[derive(Debug, Clone, PartialEq)]
struct User { name: String, age: u32, active: bool }

let user = User { name: String::from("Ferris"), age: 10, active: true };
let updated = User { age: 11, ..user.clone() };
println!("{updated:?}");
</code></pre>
<p>Common derived traits include <code>Debug</code>, <code>Clone</code>, <code>Copy</code>, <code>PartialEq</code>, <code>Eq</code>, <code>PartialOrd</code>, <code>Ord</code>, <code>Hash</code>, and <code>Default</code>. <code>Copy</code> cannot be implemented for a type that implements <code>Drop</code>.</p>
<pre><code class="language-rust">struct UserId(u64);          // Tuple struct
struct Point(i32, i32);
struct Marker;               // Unit struct
</code></pre>
<p>Methods are defined in <code>impl</code> blocks. <code>&amp;self</code> borrows, <code>&amp;mut self</code> mutably borrows, and <code>self</code> consumes the value.</p>
<pre><code class="language-rust">struct Rectangle { width: u32, height: u32 }

impl Rectangle {
    fn square(size: u32) -&gt; Self { Self { width: size, height: size } }
    fn area(&amp;self) -&gt; u32 { self.width * self.height }
    fn resize(&amp;mut self, width: u32, height: u32) {
        self.width = width; self.height = height;
    }
    fn dimensions(self) -&gt; (u32, u32) { (self.width, self.height) }
}

let mut rectangle = Rectangle::square(10);
rectangle.resize(20, 30);
assert_eq!(rectangle.area(), 600);
assert_eq!(rectangle.dimensions(), (20, 30));
</code></pre>
<h3>Unions</h3>
<p>A <code>union</code> stores all fields in shared storage. It is mainly used for FFI and low-level representations.</p>
<pre><code class="language-rust">#[repr(C)]
union Number { integer: i32, floating: f32 }

let number = Number { integer: 42 };
// SAFETY: number was initialized through integer.
let integer = unsafe { number.integer };
assert_eq!(integer, 42);
</code></pre>
<p>Writing a field is safe, but reading is <code>unsafe</code> because the compiler cannot prove that the bits are valid for the selected field. A union does not track an active field. Its fields are restricted to types that do not require ordinary drop glue, references, or wrappers such as <code>ManuallyDrop&lt;T&gt;</code>. Prefer an <code>enum</code> for ordinary safe application data.</p>
<h3>Enums and <code>Option</code></h3>
<p>Enum variants can hold different shapes of data.</p>
<pre><code class="language-rust">enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(u8, u8, u8),
}

fn handle(message: Message) {
    match message {
        Message::Quit =&gt; println!("quit"),
        Message::Move { x, y } =&gt; println!("move to {x}, {y}"),
        Message::Write(text) =&gt; println!("{text}"),
        Message::ChangeColor(r, g, b) =&gt; println!("rgb({r}, {g}, {b})"),
    }
}
handle(Message::Write(String::from("hello")));
</code></pre>
<p>Rust represents optional values with <code>Option&lt;T&gt;</code> rather than <code>null</code>.</p>
<pre><code class="language-rust">fn find_even(values: &amp;[i32]) -&gt; Option&lt;i32&gt; {
    values.iter().copied().find(|value| value % 2 == 0)
}

let value = find_even(&amp;[1, 3, 4, 5]);
assert_eq!(value, Some(4));
assert_eq!(value.map(|n| n * 2), Some(8));
assert_eq!(None::&lt;i32&gt;.unwrap_or(0), 0);
</code></pre>
<p><code>unwrap</code> and <code>expect</code> panic on <code>None</code>. For expected absence, prefer matching, <code>?</code>, or fallback methods such as <code>unwrap_or</code>.</p>
<hr />
<h2>Collections and strings</h2>
<h3><code>Vec&lt;T&gt;</code></h3>
<pre><code class="language-rust">let mut values = Vec::with_capacity(4);
values.push(10);
values.extend([20, 30]);
assert_eq!(values[0], 10);              // Panics if out of bounds.
assert_eq!(values.get(1), Some(&amp;20));   // Safe optional access.
assert_eq!(values.pop(), Some(30));

let numbers = vec![1, 2, 3];
let zeros = vec![0; 5];
</code></pre>
<h3><code>String</code> and <code>&amp;str</code></h3>
<p><code>String</code> owns a growable UTF-8 buffer; <code>&amp;str</code> borrows UTF-8 text. Read-only function parameters generally prefer <code>&amp;str</code> over <code>&amp;String</code>.</p>
<pre><code class="language-rust">let mut message = String::from("Hello");
message.push(',');
message.push_str(" Rust");

fn greet(name: &amp;str) -&gt; String { format!("Hello, {name}!") }
assert_eq!(greet(&amp;message), "Hello, Hello, Rust!");

let first = String::from("Hello");
let second = String::from("Rust");
let joined = format!("{first}, {second}"); // Does not consume either value.
let combined = first + ", " + &amp;second;     // Consumes first.
</code></pre>
<h3>Maps, sets, and queues</h3>
<pre><code class="language-rust">use std::collections::HashMap;

let mut scores = HashMap::new();
scores.insert(String::from("Alice"), 10);
scores.entry(String::from("Carol")).or_insert(0);
*scores.entry(String::from("Alice")).or_insert(0) += 5;

if let Some(score) = scores.get("Alice") { println!("{score}"); }
for (name, score) in &amp;scores { println!("{name}: {score}"); }
</code></pre>
<p>Do not depend on <code>HashMap</code> iteration order. Use <code>BTreeMap</code> when key order matters. <code>HashSet</code> stores unique values, and <code>VecDeque</code> supports efficient operations at both ends.</p>
<pre><code class="language-rust">use std::collections::{BTreeMap, HashSet, VecDeque};
let unique: HashSet&lt;_&gt; = [1, 2, 2, 3].into_iter().collect();
let mut sorted = BTreeMap::new(); sorted.insert("b", 2); sorted.insert("a", 1);
let mut queue = VecDeque::new(); queue.push_back("first");
assert_eq!(queue.pop_front(), Some("first"));
</code></pre>
<hr />
<h2>Error handling</h2>
<p>Rust uses <code>Result&lt;T, E&gt;</code> for recoverable errors and <code>panic!</code> for unrecoverable bugs.</p>
<pre><code class="language-rust">use std::{fs, io};
fn read_config() -&gt; Result&lt;String, io::Error&gt; {
    let contents = fs::read_to_string("config.toml")?;
    Ok(contents)
}
</code></pre>
<p><code>?</code> unwraps a success value and returns an error early, converting it through <code>From</code> when applicable. <code>main</code> may also return <code>Result</code>.</p>
<pre><code class="language-rust,no_run">use std::{error::Error, fs};
fn main() -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
    println!("{}", fs::read_to_string("config.toml")?);
    Ok(())
}
</code></pre>
<p>Useful combinators include <code>map</code>, <code>map_err</code>, <code>and_then</code>, <code>unwrap_or</code>, <code>unwrap_or_else</code>, <code>inspect</code>, and <code>inspect_err</code>.</p>
<pre><code class="language-rust">fn parse_number(text: &amp;str) -&gt; Result&lt;i32, String&gt; {
    text.parse::&lt;i32&gt;().map_err(|error| format!("invalid integer: {error}"))
}
assert_eq!(parse_number("42"), Ok(42));
</code></pre>
<p>Library APIs usually benefit from a concrete error type callers can inspect. Implement <code>Display</code>, <code>Error</code>, and appropriate <code>From</code> conversions; crates such as <code>thiserror</code> and <code>anyhow</code> may be useful depending on the application.</p>
<p>Use <code>unwrap</code> and <code>expect</code> mainly in tests, examples, or places where failure proves an invariant violation. Use <code>Result</code> or <code>Option</code> for ordinary input failures.</p>
<hr />
<h2>Generics, traits, and lifetimes</h2>
<pre><code class="language-rust">fn largest&lt;T: PartialOrd&gt;(values: &amp;[T]) -&gt; Option&lt;&amp;T&gt; {
    let mut iterator = values.iter();
    let mut largest = iterator.next()?;
    for value in iterator { if value &gt; largest { largest = value; } }
    Some(largest)
}
assert_eq!(largest(&amp;[3, 1, 4, 2]), Some(&amp;4));
</code></pre>
<p>Traits define shared behavior.</p>
<pre><code class="language-rust">trait Summary {
    fn summarize(&amp;self) -&gt; String;
    fn category(&amp;self) -&gt; &amp;'static str { "general" }
}

struct Article { title: String }
impl Summary for Article {
    fn summarize(&amp;self) -&gt; String { self.title.clone() }
}
</code></pre>
<p>Use <code>impl Trait</code>, explicit bounds, or <code>where</code> clauses depending on readability.</p>
<pre><code class="language-rust">use std::fmt::{Debug, Display};
fn print_summary(item: &amp;impl Display) { println!("{item}"); }
fn print_debug&lt;T: Debug&gt;(item: &amp;T) { println!("{item:?}"); }
fn compare_and_print&lt;T, U&gt;(left: &amp;T, right: &amp;U)
where T: Display + PartialOrd&lt;U&gt;, U: Display,
{ println!("{left} / {right}"); }
</code></pre>
<p>Associated types select one concrete type per trait implementation.</p>
<pre><code class="language-rust">trait Repository {
    type Item;
    type Error;
    fn find(&amp;self, id: u64) -&gt; Result&lt;Option&lt;Self::Item&gt;, Self::Error&gt;;
}
</code></pre>
<p>Generics use static dispatch; <code>dyn Trait</code> uses runtime dispatch through a vtable and allows heterogeneous values.</p>
<pre><code class="language-rust">use std::fmt::Display;
let values: Vec&lt;Box&lt;dyn Display&gt;&gt; = vec![Box::new(42), Box::new(String::from("hello"))];
</code></pre>
<p>Lifetime annotations connect the validity of references; they do not extend a value's lifetime.</p>
<pre><code class="language-rust">struct Excerpt&lt;'a&gt; { text: &amp;'a str }
impl&lt;'a&gt; Excerpt&lt;'a&gt; { fn text(&amp;self) -&gt; &amp;str { self.text } }
</code></pre>
<p>Owning a <code>String</code> instead of borrowing <code>&amp;str</code> can eliminate lifetime parameters when ownership better matches the design.</p>
<hr />
<h2>Iterators</h2>
<p>Iterator adapters are lazy; consumers such as <code>collect</code>, <code>sum</code>, and <code>find</code> drive evaluation.</p>
<pre><code class="language-rust">let result: Vec&lt;i32&gt; = (1..=10)
    .filter(|n| n % 2 == 0)
    .map(|n| n * n)
    .collect();
assert_eq!(result, vec![4, 16, 36, 64, 100]);
</code></pre>
<p><code>iter()</code> yields <code>&amp;T</code>, <code>iter_mut()</code> yields <code>&amp;mut T</code>, and <code>into_iter()</code> usually yields <code>T</code> and consumes the collection.</p>
<pre><code class="language-rust">let mut values = vec![1, 2, 3];
for value in values.iter_mut() { *value *= 2; }
assert_eq!(values, vec![2, 4, 6]);
let total: i32 = values.into_iter().sum();
assert_eq!(total, 12);
</code></pre>
<p>Implement <code>Iterator::next</code> to create an iterator.</p>
<pre><code class="language-rust">struct Counter { current: u32, end: u32 }
impl Iterator for Counter {
    type Item = u32;
    fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {
        if self.current &gt;= self.end { return None; }
        self.current += 1; Some(self.current)
    }
}
assert_eq!(Counter { current: 0, end: 3 }.collect::&lt;Vec&lt;_&gt;&gt;(), vec![1, 2, 3]);
</code></pre>
<hr />
<h2>Smart pointers</h2>
<ul>
<li><code>Box&lt;T&gt;</code> places a value on the heap with single ownership.</li>
<li><code>Rc&lt;T&gt;</code> provides reference-counted shared ownership within one thread.</li>
<li><code>Arc&lt;T&gt;</code> provides atomic reference-counted ownership across threads.</li>
<li><code>Cell&lt;T&gt;</code> and <code>RefCell&lt;T&gt;</code> provide interior mutability; <code>RefCell</code> checks borrowing at runtime and panics on violations.</li>
</ul>
<pre><code class="language-rust">enum List { Cons(i32, Box&lt;List&gt;), Nil }
let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
</code></pre>
<pre><code class="language-rust">use std::{cell::RefCell, rc::Rc};
let shared = Rc::new(String::from("shared"));
let copy = Rc::clone(&amp;shared);
assert_eq!(Rc::strong_count(&amp;shared), 2);

let values = RefCell::new(vec![1, 2]);
values.borrow_mut().push(3);
assert_eq!(*values.borrow(), vec![1, 2, 3]);
</code></pre>
<p>Rust uses RAII: resources such as locks and files are released when their owner is dropped. Implement <code>Drop</code> for custom cleanup, and call <code>drop(value)</code> to release a value before the end of its scope.</p>
<hr />
<h2>Modules, packages, and visibility</h2>
<table>
<thead>
<tr>
<th>Term</th>
<th>Meaning</th>
</tr>
</thead>
<tbody><tr>
<td>Package</td>
<td>A <code>Cargo.toml</code> definition containing one or more crates</td>
</tr>
<tr>
<td>Crate</td>
<td>A compilation unit: a binary or library</td>
</tr>
<tr>
<td>Module</td>
<td>A namespace and visibility boundary within a crate</td>
</tr>
</tbody></table>
<p>Items are private by default. <code>pub</code>, <code>pub(crate)</code>, <code>pub(super)</code>, and <code>pub(in path)</code> expose progressively scoped APIs.</p>
<pre><code class="language-rust">mod network {
    pub mod client { pub fn connect() { println!("connected"); } }
    fn private_helper() {}
}
use network::client;
fn main() { client::connect(); }
</code></pre>
<p>Typical files include <code>src/main.rs</code> for a binary root, <code>src/lib.rs</code> for a library root, and files or subdirectories for modules. Both <code>network.rs</code> plus <code>network/client.rs</code> and the older <code>network/mod.rs</code> layout are supported.</p>
<pre><code class="language-rust">use std::collections::HashMap;
use std::fmt::{self, Display};
use std::io::Result as IoResult;

mod models { pub struct User; }
pub use models::User; // Re-export from a crate root.
</code></pre>
<hr />
<h2>Concurrency</h2>
<p>Ownership plus the <code>Send</code> and <code>Sync</code> traits lets Rust reject many concurrency mistakes at compile time.</p>
<pre><code class="language-rust">use std::thread;
let values = vec![1, 2, 3];
let handle = thread::spawn(move || values.iter().sum::&lt;i32&gt;());
assert_eq!(handle.join().expect("thread panicked"), 6);

let borrowed = vec![1, 2, 3];
thread::scope(|scope| { scope.spawn(|| println!("{borrowed:?}")); });
</code></pre>
<p>The standard <code>mpsc</code> channel supports multiple producers and one consumer.</p>
<pre><code class="language-rust">use std::{sync::mpsc, thread};
let (sender, receiver) = mpsc::channel();
for id in 0..2 {
    let sender = sender.clone();
    thread::spawn(move || sender.send(format!("worker {id}")).unwrap());
}
drop(sender);
for message in receiver { println!("{message}"); }
</code></pre>
<p>Use <code>Arc&lt;Mutex&lt;T&gt;&gt;</code> for mutable state shared across threads. Lock guards release automatically when dropped; keep critical sections short and acquire multiple locks in a consistent order.</p>
<pre><code class="language-rust">use std::{sync::{Arc, Mutex}, thread};
let counter = Arc::new(Mutex::new(0));
let handles: Vec&lt;_&gt; = (0..10).map(|_| {
    let counter = Arc::clone(&amp;counter);
    thread::spawn(move || *counter.lock().expect("poisoned mutex") += 1)
}).collect();
for handle in handles { handle.join().unwrap(); }
assert_eq!(*counter.lock().unwrap(), 10);
</code></pre>
<p><code>Send</code> means ownership can move to another thread; <code>Sync</code> means <code>&amp;T</code> can be shared across threads. Manual <code>unsafe impl</code> requires the author to uphold the full safety contract.</p>
<p>Rust supplies <code>Future</code> and async syntax, but the standard library does not provide a general-purpose async runtime. Choose a runtime such as Tokio when the I/O requirements call for one.</p>
<pre><code class="language-rust">async fn fetch_value() -&gt; u32 { 42 }
async fn calculate() -&gt; u32 { fetch_value().await * 2 }
</code></pre>
<p>Calling an <code>async fn</code> creates a lazy <code>Future</code>; work progresses only when it is awaited or driven by an executor.</p>
<hr />
<h2>Macros and attributes</h2>
<p>Common macros include <code>println!</code>, <code>eprintln!</code>, <code>format!</code>, <code>vec!</code>, <code>assert!</code>, <code>assert_eq!</code>, and <code>assert_ne!</code>. <code>todo!</code>, <code>unimplemented!</code>, and <code>unreachable!</code> panic if executed.</p>
<pre><code class="language-rust">macro_rules! hash_map {
    ($($key:expr =&gt; $value:expr),* $(,)?) =&gt; {{
        let mut map = std::collections::HashMap::new();
        $(map.insert($key, $value);)*
        map
    }};
}
let scores = hash_map! { "Alice" =&gt; 10, "Bob" =&gt; 20 };
</code></pre>
<p>Procedural macros include custom derives, attribute macros, and function-like macros, and are defined in a separate <code>proc-macro</code> crate.</p>
<pre><code class="language-rust">#[derive(Debug, Clone, PartialEq)]
struct User;

#[cfg(target_os = "linux")]
fn platform_name() -&gt; &amp;'static str { "Linux" }

#[must_use]
fn calculate() -&gt; i32 { 42 }
</code></pre>
<p><code>#[cfg(feature = "json")]</code> enables conditional compilation for Cargo features.</p>
<hr />
<h2>Testing</h2>
<pre><code class="language-rust">pub fn add(left: i32, right: i32) -&gt; i32 { left + right }

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn adds_numbers() { assert_eq!(add(2, 3), 5); }

    #[test]
    fn parses_number() -&gt; Result&lt;(), Box&lt;dyn std::error::Error&gt;&gt; {
        assert_eq!("42".parse::&lt;i32&gt;()?, 42); Ok(())
    }
}
</code></pre>
<p>Files under <code>tests/</code> are separate crates that test a library's public API. Documentation code blocks attached to <code>///</code> comments are tested by default.</p>
<pre><code class="language-bash">cargo test
cargo test name_filter
cargo test -- --nocapture
cargo test -- --ignored
cargo test --doc
cargo test --all-features
</code></pre>
<hr />
<h2>Standard-library quick reference</h2>
<pre><code class="language-rust">let name = "Ferris";
println!("{name:&gt;8}");
println!("hex: {:x}, binary: {:b}", 10, 10);

let text = "  Hello, Rust  ";
assert_eq!(text.trim(), "Hello, Rust");
assert_eq!("a,b,c".split(',').collect::&lt;Vec&lt;_&gt;&gt;(), vec!["a", "b", "c"]);
assert_eq!(["a", "b", "c"].join("-"), "a-b-c");
</code></pre>
<pre><code class="language-rust">fn main() -&gt; Result&lt;(), Box&lt;dyn std::error::Error&gt;&gt; {
    let number: i32 = "42".parse()?;
    let hex = i32::from_str_radix("ff", 16)?;
    assert_eq!((number.to_string(), hex), (String::from("42"), 255));
    Ok(())
}
</code></pre>
<p>Use <code>fs::read_to_string</code> and <code>fs::write</code> for small files, or <code>BufReader</code> and <code>BufRead::lines</code> for streaming large files. Build paths with <code>Path</code> and <code>PathBuf</code>. Read arguments with <code>env::args</code> and environment variables with <code>env::var</code>; never print secrets in logs or error messages.</p>
<p>Use <code>Instant</code> for elapsed time, <code>SystemTime</code> for system-clock values, and <code>Duration</code> for spans. Date formatting and time zones generally require a suitable external crate.</p>
<p><code>OnceLock&lt;T&gt;</code> initializes a global value once; <code>LazyLock&lt;T&gt;</code> initializes it from a closure on first access.</p>
<pre><code class="language-rust">use std::sync::{LazyLock, OnceLock};
static CONFIG: OnceLock&lt;String&gt; = OnceLock::new();
static DEFAULTS: LazyLock&lt;Vec&lt;String&gt;&gt; = LazyLock::new(|| vec![String::from("default")]);
assert_eq!(CONFIG.get_or_init(|| String::from("production")), "production");
assert_eq!(DEFAULTS.len(), 1);
</code></pre>
<hr />
<h2>Calling external functions: <code>extern</code> and FFI</h2>
<p><code>extern "C"</code> selects the C ABI. In Edition 2024, external blocks must be declared with <code>unsafe extern</code> because Rust cannot verify that their signatures match the foreign definitions.</p>
<pre><code class="language-rust,no_run">use std::ffi::c_int;
unsafe extern "C" { fn abs(input: c_int) -&gt; c_int; }
// SAFETY: -42 is a valid c_int input for C abs.
assert_eq!(unsafe { abs(-42) }, 42);
</code></pre>
<p>Export a Rust function with a C ABI as follows:</p>
<pre><code class="language-rust">#[unsafe(no_mangle)]
pub extern "C" fn add(left: i32, right: i32) -&gt; i32 { left + right }
assert_eq!(add(2, 3), 5);
</code></pre>
<p>At an FFI boundary, verify the ABI and signatures, <code>#[repr(C)]</code> layouts, pointer validity and alignment, string encoding and termination, allocation ownership, and panic or exception behavior. Generated bindings such as bindgen may reduce transcription mistakes.</p>
<hr />
<h2><code>unsafe</code> Rust</h2>
<p><code>unsafe</code> does not disable the borrow checker. It permits a small set of operations whose safety the compiler cannot prove: dereferencing raw pointers, calling unsafe functions, accessing mutable statics, implementing unsafe traits, and reading union fields.</p>
<pre><code class="language-rust">unsafe fn first_unchecked(values: &amp;[i32]) -&gt; &amp;i32 {
    // SAFETY: The caller guarantees that values is non-empty.
    unsafe { values.get_unchecked(0) }
}
let values = [10, 20];
// SAFETY: values contains two elements.
assert_eq!(*unsafe { first_unchecked(&amp;values) }, 10);
</code></pre>
<p>Edition 2024 still requires an explicit <code>unsafe</code> block inside an <code>unsafe fn</code>. Keep unsafe regions small, document invariants with <code>SAFETY</code> comments, and ensure every safe wrapper preserves those invariants for all safe callers.</p>
<hr />
<h2>Cargo and dependency management</h2>
<pre><code class="language-bash">cargo new app
cargo new --lib my-library
cargo check
cargo build --release
cargo run -- arg1 arg2
cargo test
cargo doc --open
cargo fmt --check
cargo clippy --all-targets --all-features -- -D warnings
</code></pre>
<p><code>cargo check</code> is fast because it does not produce a final binary. Still run builds and tests before release.</p>
<pre><code class="language-toml">[package]
name = "example"
version = "0.1.0"
edition = "2024"
rust-version = "1.98"
</code></pre>
<p><code>edition</code> selects language compatibility rules; <code>rust-version</code> declares the MSRV actually supported and tested by the package.</p>
<pre><code class="language-bash">cargo add serde --features derive
cargo add --dev tempfile
cargo update
cargo tree
cargo tree -d
</code></pre>
<p><code>Cargo.lock</code> records an exact dependency resolution. Applications normally commit it. Libraries may also commit a workspace lockfile for reproducible development and CI, while consumers still resolve versions from <code>Cargo.toml</code> constraints.</p>
<p>Features should be additive. Test meaningful combinations with <code>--all-features</code> and <code>--no-default-features</code>. A workspace can share <code>edition</code>, <code>rust-version</code>, and dependency declarations through <code>[workspace.package]</code> and <code>[workspace.dependencies]</code>; Edition 2024 workspaces use <code>resolver = "3"</code>.</p>
<hr />
<h2>Tips and common mistakes</h2>
<h3>Avoid reflexive <code>clone</code></h3>
<p>Borrow when ownership is unnecessary; cloning may hide a design problem and add allocations.</p>
<pre><code class="language-rust">fn print_name(name: &amp;str) { println!("{name}"); }
let name = String::from("Ferris");
print_name(&amp;name);
println!("{name}");
</code></pre>
<h3>Prefer slices in read-only APIs</h3>
<p>Use <code>&amp;str</code> instead of <code>&amp;String</code>, and <code>&amp;[T]</code> instead of <code>&amp;Vec&lt;T&gt;</code>, unless the concrete container is required.</p>
<h3>Use checked indexing for uncertain input</h3>
<p><code>values[index]</code> panics out of bounds; <code>values.get(index)</code> returns <code>Option&lt;&amp;T&gt;</code>.</p>
<h3>Remember that strings are UTF-8</h3>
<pre><code class="language-rust">let text = "🦀Rust";
assert_eq!(text.len(), 8); // Bytes, not visible characters.
assert_eq!(text.chars().next(), Some('🦀'));
</code></pre>
<p>Rust strings have no integer indexing. Use an appropriate Unicode crate when grapheme-cluster processing is required.</p>
<h3>Do not hold a synchronous mutex guard across <code>.await</code></h3>
<pre><code class="language-rust">use std::sync::Mutex;
async fn async_operation(_value: String) {}
async fn process(shared: &amp;Mutex&lt;String&gt;) {
    let value = { shared.lock().expect("poisoned mutex").clone() };
    async_operation(value).await;
}
</code></pre>
<p>Release the guard first, or choose an async-aware mutex when appropriate. Likewise, move blocking I/O or CPU-heavy work off an async executor's worker threads using the runtime's blocking API or dedicated threads.</p>
<h3>Document panics in public APIs</h3>
<p>Ordinary invalid input should generally return <code>Result</code> or <code>Option</code>. If a public function can panic, document the condition in a <code># Panics</code> section.</p>
<h3>Keep warnings clean</h3>
<pre><code class="language-bash">cargo fmt --check
cargo clippy --all-targets --all-features -- -D warnings
cargo test --all-features
</code></pre>
<p>Review Clippy suggestions before applying them; they can affect semantics or performance. Follow project-specific lint policy where one exists.</p>
<hr />
<h2>Official references</h2>
<ul>
<li><a href="https://www.rust-lang.org/">Rust</a></li>
<li><a href="https://doc.rust-lang.org/stable/book/">The Rust Programming Language</a></li>
<li><a href="https://doc.rust-lang.org/rust-by-example/">Rust By Example</a></li>
<li><a href="https://doc.rust-lang.org/reference/">The Rust Reference</a></li>
<li><a href="https://doc.rust-lang.org/std/">Standard Library</a></li>
<li><a href="https://doc.rust-lang.org/cargo/">The Cargo Book</a></li>
<li><a href="https://doc.rust-lang.org/clippy/">Clippy Documentation</a></li>
<li><a href="https://doc.rust-lang.org/edition-guide/">The Rust Edition Guide</a></li>
<li><a href="https://blog.rust-lang.org/2026/08/20/Rust-1.98.0/">Rust 1.98.0 release notes</a></li>
</ul>
<p>Rust works best when ownership, borrowing, and types make invalid states difficult to represent. Compiler errors are not merely restrictions—they are early feedback about the design.</p>
]]></content:encoded></item><item><title><![CDATA[Rust チートシート]]></title><description><![CDATA[Rust 1.98・Edition 2024対応のチートシート。基本構文から所有権・借用、ライフタイム、トレイト、エラーハンドリング、並行処理、Cargoまで、コード例で使い方を確認できます。]]></description><link>https://nobuo-miura.hashnode.dev/rust</link><guid isPermaLink="true">https://nobuo-miura.hashnode.dev/rust</guid><category><![CDATA[Rust]]></category><category><![CDATA[rust lang]]></category><category><![CDATA[cheatsheet]]></category><dc:creator><![CDATA[Nobuo Miura]]></dc:creator><pubDate>Fri, 27 Nov 2026 10:37:07 GMT</pubDate><content:encoded><![CDATA[<p>Rust 1.98・Edition 2024をベースにしたチートシートです。</p>
<hr />
<h2>インストール・更新</h2>
<p><a href="https://rust-lang.org/tools/install/">Rust公式 - Install Rust</a></p>
<p>Rustのツールチェーンは、公式の <code>rustup</code> で管理する方法が推奨されています。macOS、Linux、WSLなどのUnix系環境では、公式サイトに掲載されている次のコマンドでインストーラを起動します。</p>
<pre><code class="language-bash">curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
</code></pre>
<p>Windowsでは<a href="https://rust-lang.org/tools/install/">公式インストールページ</a>から <code>rustup-init.exe</code> を取得して実行します。環境によってはVisual StudioのC++ Build Toolsも必要です。</p>
<p>インストール後はターミナルを開き直し、バージョンを確認します。</p>
<pre><code class="language-bash">rustc --version
cargo --version
rustup --version
</code></pre>
<p>安定版ツールチェーンの更新と、フォーマッタ・linterの追加は次のように行います。</p>
<pre><code class="language-bash">rustup update stable
rustup component add rustfmt clippy
</code></pre>
<p>既存プロジェクトに <code>rust-toolchain.toml</code> や <code>rust-toolchain</code> がある場合は、その指定を優先します。ライブラリでは <code>Cargo.toml</code> の <code>rust-version</code> でサポートする最小Rustバージョン（MSRV）を示せます。</p>
<hr />
<h2>基本構造</h2>
<pre><code class="language-rust">fn main() {
    println!("Hello, Rust 1.98!");
}
</code></pre>
<ul>
<li>実行可能バイナリのエントリポイントは <code>main</code> 関数</li>
<li>文は通常 <code>;</code> で終える</li>
<li><code>println!</code> のように <code>!</code> が付くものはマクロ</li>
</ul>
<h3>コメント</h3>
<table>
<thead>
<tr>
<th>構文</th>
<th>用途</th>
</tr>
</thead>
<tbody><tr>
<td><code>// ...</code></td>
<td>行末までの通常コメント</td>
</tr>
<tr>
<td><code>/* ... */</code></td>
<td>複数行にまたがる通常コメント。入れ子にできる</td>
</tr>
<tr>
<td><code>/// ...</code>, <code>/** ... */</code></td>
<td>直後の項目を説明する外部ドキュメントコメント</td>
</tr>
<tr>
<td><code>//! ...</code>, <code>/*! ... */</code></td>
<td>crateやmodule自身を説明する内部ドキュメントコメント</td>
</tr>
</tbody></table>
<pre><code class="language-rust">// 行コメント
let value = 42;

/* ブロックコメントは
   複数行に記述できる */
assert_eq!(value, 42);
</code></pre>
<p>ドキュメントコメントはMarkdownとして処理され、<code>cargo doc</code> で生成されるAPIドキュメントに反映されます。コードブロックは通常 <code>cargo test</code> でドキュメントテストとして実行されます。</p>
<pre><code class="language-rust">mod math {
    //! 基本的な計算機能を提供します。

    /// 2つの整数を加算します。
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(2 + 3, 5);
    /// ```
    pub fn add(left: i32, right: i32) -&gt; i32 {
        left + right
    }
}

assert_eq!(math::add(2, 3), 5);
</code></pre>
<p>Cargoでプロジェクトを作成・実行します。</p>
<pre><code class="language-bash">cargo new hello-rust
cd hello-rust
cargo run
</code></pre>
<p><code>cargo new</code> で作成したプロジェクトは、<code>Cargo.toml</code> に <code>edition = "2024"</code> が設定されます。</p>
<h3>キーワード</h3>
<p><a href="https://doc.rust-lang.org/reference/keywords.html">公式リファレンス - キーワード</a></p>
<p>Rustのキーワードは、常に特別な意味を持つ厳密キーワード、将来のために確保された予約キーワード、特定の文脈だけで意味を持つ弱いキーワードに分類されます。</p>
<h4>厳密キーワード</h4>
<table>
<thead>
<tr>
<th>キーワード</th>
<th>主な用途</th>
</tr>
</thead>
<tbody><tr>
<td><code>_</code></td>
<td>パターンで値を無視する、または型・値などを推論させるプレースホルダー</td>
</tr>
<tr>
<td><code>as</code></td>
<td>プリミティブ型のキャスト、<code>use</code>での別名、完全修飾構文</td>
</tr>
<tr>
<td><code>async</code></td>
<td><code>Future</code>を返す非同期関数・ブロック・クロージャを定義</td>
</tr>
<tr>
<td><code>await</code></td>
<td><code>Future</code>の完了まで現在の非同期処理を一時停止</td>
</tr>
<tr>
<td><code>break</code></td>
<td>ループを終了し、必要に応じて値を返す</td>
</tr>
<tr>
<td><code>const</code></td>
<td>コンパイル時定数、const関数・ブロック・ジェネリクスなどを指定</td>
</tr>
<tr>
<td><code>continue</code></td>
<td>現在のループ反復の残りを飛ばして次へ進む</td>
</tr>
<tr>
<td><code>crate</code></td>
<td>現在のcrate、またはcrateルートを参照</td>
</tr>
<tr>
<td><code>dyn</code></td>
<td>実行時に動的ディスパッチするトレイトオブジェクトを表す</td>
</tr>
<tr>
<td><code>else</code></td>
<td><code>if</code>・<code>if let</code>の条件が成立しない場合の分岐</td>
</tr>
<tr>
<td><code>enum</code></td>
<td>複数のバリアントを持つ列挙型を定義</td>
</tr>
<tr>
<td><code>extern</code></td>
<td>外部ABI、外部関数・static、外部crateを扱う</td>
</tr>
<tr>
<td><code>false</code></td>
<td><code>bool</code>型の偽リテラル</td>
</tr>
<tr>
<td><code>fn</code></td>
<td>関数または関数ポインタ型を定義</td>
</tr>
<tr>
<td><code>for</code></td>
<td>イテレータによるループ、または対象型へのトレイト実装を記述</td>
</tr>
<tr>
<td><code>if</code></td>
<td>条件に応じて式を分岐</td>
</tr>
<tr>
<td><code>impl</code></td>
<td>型のメソッドやトレイト実装を定義</td>
</tr>
<tr>
<td><code>in</code></td>
<td><code>for</code>ループで反復対象を指定</td>
</tr>
<tr>
<td><code>let</code></td>
<td>パターンへ値を束縛して変数を宣言</td>
</tr>
<tr>
<td><code>loop</code></td>
<td>明示的に終了するまで繰り返すループを作成</td>
</tr>
<tr>
<td><code>match</code></td>
<td>パターンマッチによって網羅的に分岐</td>
</tr>
<tr>
<td><code>mod</code></td>
<td>moduleを宣言・定義</td>
</tr>
<tr>
<td><code>move</code></td>
<td>クロージャなどへキャプチャした値を移動</td>
</tr>
<tr>
<td><code>mut</code></td>
<td>変数、参照、パターンなどを可変として指定</td>
</tr>
<tr>
<td><code>pub</code></td>
<td>項目を指定した範囲へ公開</td>
</tr>
<tr>
<td><code>ref</code></td>
<td>パターン内で値を移動せず参照として束縛</td>
</tr>
<tr>
<td><code>return</code></td>
<td>関数から値を早期に返す</td>
</tr>
<tr>
<td><code>self</code></td>
<td>メソッドのレシーバー、または現在のmoduleを参照</td>
</tr>
<tr>
<td><code>Self</code></td>
<td>現在定義・実装している型自身を参照</td>
</tr>
<tr>
<td><code>static</code></td>
<td>固定された格納場所を持つstatic項目を定義</td>
</tr>
<tr>
<td><code>struct</code></td>
<td>名前付き・タプル形式・ユニット形式の構造体を定義</td>
</tr>
<tr>
<td><code>super</code></td>
<td>親moduleを参照</td>
</tr>
<tr>
<td><code>trait</code></td>
<td>型が共有できる振る舞いを定義</td>
</tr>
<tr>
<td><code>true</code></td>
<td><code>bool</code>型の真リテラル</td>
</tr>
<tr>
<td><code>type</code></td>
<td>型エイリアスまたは関連型を定義</td>
</tr>
<tr>
<td><code>unsafe</code></td>
<td>コンパイラだけでは安全性を保証できない操作や契約を明示</td>
</tr>
<tr>
<td><code>use</code></td>
<td>パスを現在のスコープへ導入、または項目を再公開</td>
</tr>
<tr>
<td><code>where</code></td>
<td>ジェネリクスやライフタイムの境界条件を記述</td>
</tr>
<tr>
<td><code>while</code></td>
<td>条件が成立している間ループを繰り返す</td>
</tr>
</tbody></table>
<h4>予約キーワード</h4>
<p><code>abstract</code>, <code>become</code>, <code>box</code>, <code>do</code>, <code>final</code>, <code>gen</code>, <code>macro</code>, <code>override</code>, <code>priv</code>, <code>try</code>, <code>typeof</code>, <code>unsized</code>, <code>virtual</code>, <code>yield</code></p>
<p>これらは将来の言語拡張のために予約されています。Rust 1.98ではキーワードとしての機能を持たず、通常の識別子にも使用できません。<code>typeof</code> も予約されていますが、型を取得する演算子としては実装されていません。</p>
<h4>弱いキーワード</h4>
<table>
<thead>
<tr>
<th>キーワード</th>
<th>意味を持つ文脈</th>
</tr>
</thead>
<tbody><tr>
<td><code>'static</code></td>
<td>プログラム全体にわたって有効なライフタイム</td>
</tr>
<tr>
<td><code>macro_rules</code></td>
<td>宣言的マクロを定義</td>
</tr>
<tr>
<td><code>raw</code></td>
<td><code>&amp;raw const</code>・<code>&amp;raw mut</code>による生ポインタの作成</td>
</tr>
<tr>
<td><code>safe</code></td>
<td><code>unsafe extern</code>ブロック内で、安全に呼び出せる関数・staticを宣言</td>
</tr>
<tr>
<td><code>union</code></td>
<td>複数フィールドがストレージを共有する共用体を定義</td>
</tr>
</tbody></table>
<p>識別子にキーワードと同じ名前が必要な場合は、利用可能な文脈に限り <code>r#type</code> のようなraw identifierを使えます。</p>
<hr />
<h2>変数・定数・基本型</h2>
<h3>変数宣言</h3>
<p>Rustの変数はデフォルトで不変です。値を変更する場合は <code>mut</code> を付けます。</p>
<pre><code class="language-rust">let name = "Ferris";       // 型推論により &amp;str
let age: u32 = 10;         // 型を明示
let mut count = 0;         // 可変変数
count += 1;

// パターンで分割代入
let (x, y) = (10, 20);

// 使用前に必ず初期化すれば、宣言時の初期値は省略できる
let status: String;
status = String::from("ready");
println!("{status}");
</code></pre>
<h3>シャドーイング</h3>
<p>同じ名前を <code>let</code> で再宣言できます。<code>mut</code> と異なり、型も変更できます。</p>
<pre><code class="language-rust">let spaces = "   ";
let spaces = spaces.len(); // &amp;str から usize に変更
</code></pre>
<h3>定数・static</h3>
<pre><code class="language-rust">const MAX_RETRIES: u32 = 3;
static APPLICATION_NAME: &amp;str = "example";
</code></pre>
<ul>
<li><code>const</code> はコンパイル時に評価される値。型の明示が必要</li>
<li><code>static</code> はプログラム全体で固定されたメモリアドレスを持つ値</li>
<li>可変な <code>static mut</code> へのアクセスは <code>unsafe</code> が必要で、通常は同期プリミティブなどを検討する</li>
</ul>
<p>複数スレッドから安全に更新する単純なカウンターには、アトミック型を利用できます。</p>
<pre><code class="language-rust">use std::sync::atomic::{AtomicU64, Ordering};

static REQUEST_COUNT: AtomicU64 = AtomicU64::new(0);

fn next_request_count() -&gt; u64 {
    REQUEST_COUNT.fetch_add(1, Ordering::Relaxed) + 1
}

assert_eq!(next_request_count(), 1);
assert_eq!(next_request_count(), 2);
</code></pre>
<p>この例の <code>Relaxed</code> は、カウンター自身の不可分な更新だけが必要で、ほかのメモリアクセスとの順序を同期しない場合に適しています。状態間の順序保証が必要な処理では、要件に合う <code>Ordering</code> やロックを選びます。</p>
<h3>値とリテラル</h3>
<p>リテラルはソースコードに直接記述する値です。数値には型サフィックスを付けられ、<code>_</code> は桁区切りとして無視されます。</p>
<pre><code class="language-rust">let integer = 42;              // i32
let unsigned = 42_u64;         // u64
let floating = 3.14_f32;       // f32
let enabled = true;            // bool
let character = 'R';           // char
let text = "Rust";             // &amp;str
let byte = b'R';               // u8
let bytes = b"Rust";           // &amp;[u8; 4]
let raw = r#"\をエスケープしない文字列"#;
let million = 1_000_000;

assert_eq!(integer, 42);
assert_eq!(bytes, &amp;[82, 117, 115, 116]);
assert!(raw.contains('\\'));
assert_eq!(million, 1_000_000);
</code></pre>
<p><code>String::from("Rust")</code> のような呼び出しで作られる値や、<code>left + right</code> のような式の評価結果も値です。Rustでは多くの構文が式であり、ブロック、<code>if</code>、<code>match</code>、<code>loop</code> も値を返せます。</p>
<h3>スカラー型</h3>
<p><a href="https://doc.rust-lang.org/reference/types.html">公式リファレンス - 型</a></p>
<table>
<thead>
<tr>
<th>分類</th>
<th>型</th>
<th>補足</th>
</tr>
</thead>
<tbody><tr>
<td>符号付き整数</td>
<td><code>i8</code>, <code>i16</code>, <code>i32</code>, <code>i64</code>, <code>i128</code>, <code>isize</code></td>
<td>数値リテラルのデフォルトは <code>i32</code></td>
</tr>
<tr>
<td>符号なし整数</td>
<td><code>u8</code>, <code>u16</code>, <code>u32</code>, <code>u64</code>, <code>u128</code>, <code>usize</code></td>
<td><code>usize</code> は添字やサイズで使用</td>
</tr>
<tr>
<td>浮動小数点</td>
<td><code>f32</code>, <code>f64</code></td>
<td>デフォルトは <code>f64</code></td>
</tr>
<tr>
<td>真偽値</td>
<td><code>bool</code></td>
<td><code>true</code>, <code>false</code></td>
</tr>
<tr>
<td>文字</td>
<td><code>char</code></td>
<td>Unicodeスカラー値（4バイト）</td>
</tr>
<tr>
<td>ユニット</td>
<td><code>()</code></td>
<td>値を返さないことを表す</td>
</tr>
</tbody></table>
<pre><code class="language-rust">let decimal = 98_222;
let hex = 0xff;
let octal = 0o77;
let binary = 0b1111_0000;
let byte = b'A'; // u8

let ratio = 3.5_f64;
let enabled = true;
let crab = '🦀';
</code></pre>
<p>デバッグビルドでは整数オーバーフローが実行時に検出されます。意図的に回り込ませる場合は <code>wrapping_add</code> などを使います。</p>
<pre><code class="language-rust">let value = u8::MAX;
assert_eq!(value.wrapping_add(1), 0);
assert_eq!(value.saturating_add(1), u8::MAX);
assert_eq!(value.checked_add(1), None);
</code></pre>
<h3>複合型</h3>
<pre><code class="language-rust">// タプル：異なる型をまとめられる
let user = ("Ferris", 10, true);
let (name, age, active) = user;
println!("{name}: {age}, active={active}");

// 配列：長さが型の一部で、スタック上に固定長で確保される
let numbers: [i32; 3] = [10, 20, 30];
let zeros = [0; 5];
println!("{} {}", numbers[0], zeros.len());
</code></pre>
<p>配列への <code>[]</code> アクセスは、範囲外の場合にpanicします。安全に取得するには <code>get</code> を使います。</p>
<pre><code class="language-rust">let values = [10, 20, 30];
match values.get(5) {
    Some(value) =&gt; println!("{value}"),
    None =&gt; println!("範囲外です"),
}
</code></pre>
<h3>型変換</h3>
<p>数値型は暗黙変換されません。<code>as</code> または <code>From</code> / <code>TryFrom</code> を使います。</p>
<pre><code class="language-rust">let small: u8 = 42;
let large = u32::from(small); // 損失のない変換

let integer = 42_i32;
let floating = integer as f64; // プリミティブ型のキャスト
assert_eq!(floating, 42.0);

let value: i32 = 300;
let byte = u8::try_from(value); // Result&lt;u8, TryFromIntError&gt;
assert!(byte.is_err());

let integer = 65_u32;
let letter = char::from_u32(integer); // Option&lt;char&gt;
assert_eq!(letter, Some('A'));
</code></pre>
<p><code>as</code> は切り詰めなどが発生し得ます。入力値の範囲を保証できない場合は <code>TryFrom</code> を優先します。</p>
<pre><code class="language-rust">let value = 300_u16;
assert_eq!(value as u8, 44); // 上位ビットが切り捨てられる
assert!(u8::try_from(value).is_err());
</code></pre>
<h3>型エイリアス</h3>
<p>型エイリアスは既存の型に別名を付けます。新しい型は作られないため、元の型と相互に代入できます。</p>
<pre><code class="language-rust">type UserId = u64;
type IoResult&lt;T&gt; = Result&lt;T, std::io::Error&gt;;

fn load_user(id: UserId) -&gt; IoResult&lt;String&gt; {
    Ok(format!("user-{id}"))
}

let id: UserId = 42;
let raw_id: u64 = id; // 同じ型として扱われる
assert_eq!(load_user(raw_id).unwrap(), "user-42");
</code></pre>
<p>値を混同できない別の型にしたい場合は、タプル構造体を使うnewtypeパターンを検討します。</p>
<pre><code class="language-rust">struct UserId(u64);
struct ProductId(u64);

fn find_user(id: UserId) {
    println!("user={}", id.0);
}

find_user(UserId(42));
// find_user(ProductId(42)); // 異なる型なのでコンパイルエラー
</code></pre>
<h3>型を調べる</h3>
<p><a href="https://doc.rust-lang.org/std/any/fn.type_name.html">標準ライブラリ - std::any::type_name</a></p>
<p>Rustに組み込みの <code>typeof</code> 演算子はありません。型を明示して取得する場合は <code>std::any::type_name::&lt;T&gt;()</code>、値から確認する場合は <code>std::any::type_name_of_val</code> を利用できます。</p>
<pre><code class="language-rust">fn type_of&lt;T: ?Sized&gt;(_: &amp;T) -&gt; &amp;'static str {
    std::any::type_name::&lt;T&gt;()
}

let number = 123;
println!("{}", type_of(&amp;number));
println!("{}", std::any::type_name_of_val(&amp;number));
</code></pre>
<p>値を直接受け取るヘルパーとして、次の形でも動作します。</p>
<pre><code class="language-rust">fn type_of&lt;T&gt;(_: T) -&gt; &amp;'static str {
    std::any::type_name::&lt;T&gt;()
}

let number = 123;
println!("{}", type_of(number));
</code></pre>
<p>ただし、この形は引数を値で受け取るため、<code>String</code> などの <code>Copy</code> ではない値を渡すと所有権が関数へ移動します。汎用ヘルパーとしては参照を受け取る形が扱いやすくなります。</p>
<p><code>type_name</code> の出力形式は保証されておらず、コンパイラのバージョンによって変わる可能性があります。型の一意な識別やアプリケーションの分岐条件には使わず、診断やログ表示に利用します。</p>
<h3>演算子</h3>
<table>
<thead>
<tr>
<th>分類</th>
<th>演算子</th>
<th>補足</th>
</tr>
</thead>
<tbody><tr>
<td>算術</td>
<td><code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, <code>%</code></td>
<td>整数同士の除算は小数部を切り捨てる</td>
</tr>
<tr>
<td>単項</td>
<td><code>-</code>, <code>!</code></td>
<td>数値の符号反転、真偽値の否定・整数のビット反転</td>
</tr>
<tr>
<td>比較</td>
<td><code>==</code>, <code>!=</code>, <code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, <code>&gt;=</code></td>
<td>型に応じて <code>PartialEq</code> / <code>PartialOrd</code> などを利用</td>
</tr>
<tr>
<td>論理</td>
<td><code>&amp;&amp;</code>, <code>||</code>, <code>!</code></td>
<td><code>&amp;&amp;</code> と <code>||</code> は短絡評価</td>
</tr>
<tr>
<td>ビット</td>
<td><code>&amp;</code>, <code>|</code>, <code>^</code>, <code>&lt;&lt;</code>, <code>&gt;&gt;</code></td>
<td>整数のビット演算</td>
</tr>
<tr>
<td>代入</td>
<td><code>=</code>, <code>+=</code>, <code>-=</code>, <code>*=</code>, <code>/=</code>, <code>%=</code>, <code>&amp;=</code>, <code>|=</code>, <code>^=</code>, <code>&lt;&lt;=</code>, <code>&gt;&gt;=</code></td>
<td>複合代入を含む</td>
</tr>
<tr>
<td>範囲</td>
<td><code>..</code>, <code>..=</code></td>
<td>終端を含まない／含む範囲</td>
</tr>
<tr>
<td>借用・デリファレンス</td>
<td><code>&amp;</code>, <code>&amp;mut</code>, <code>*</code></td>
<td>参照の作成と参照先へのアクセス</td>
</tr>
<tr>
<td>エラー伝播</td>
<td><code>?</code></td>
<td><code>Result</code> / <code>Option</code> などの失敗を早期リターン</td>
</tr>
</tbody></table>
<pre><code class="language-rust">assert_eq!(7 / 2, 3);
assert_eq!(7.0 / 2.0, 3.5);
assert_eq!(-5_i32, 0 - 5);
assert_eq!(!true, false);

let mut value = 5;
value *= 2;
assert_eq!(value, 10);

let mut flags = 0b0011_u8;
flags |= 0b0100;
flags &lt;&lt;= 1;
assert_eq!(flags, 0b1110);

let in_range = (1..=10).contains(&amp;value);
assert!(in_range);
</code></pre>
<p>ユーザー定義型では、<code>Add</code>、<code>PartialEq</code>、<code>Index</code> などの標準トレイトを実装することで対応する演算子を利用できます。任意の新しい演算子を定義したり、演算子の優先順位を変更したりすることはできません。</p>
<hr />
<h2>所有権・借用・スライス</h2>
<p><a href="https://doc.rust-lang.org/stable/book/ch04-00-understanding-ownership.html">The Rust Programming Language - 所有権</a></p>
<p>Rustはガベージコレクタを使わず、所有権の規則をコンパイル時に検査してメモリを管理します。</p>
<h3>所有権</h3>
<p>基本規則は次の3つです。</p>
<ol>
<li>各値には所有者が1つ存在する</li>
<li>同時に存在できる所有者は1つだけ</li>
<li>所有者がスコープを抜けると値は破棄される</li>
</ol>
<pre><code class="language-rust">let original = String::from("hello");
let moved = original; // Stringの所有権がmovedへ移動

println!("{moved}");
// println!("{original}"); // コンパイルエラー：移動後は使えない
</code></pre>
<p><code>i32</code> のように <code>Copy</code> を実装する型は、代入時に値がコピーされます。</p>
<pre><code class="language-rust">let x = 5;
let y = x;
println!("{x} {y}"); // どちらも使用できる
</code></pre>
<p>独立したヒープデータを複製する場合は <code>clone</code> を使います。</p>
<pre><code class="language-rust">let original = String::from("hello");
let cloned = original.clone();
println!("{original} {cloned}");
</code></pre>
<h3>借用と参照</h3>
<p>参照を渡すと、所有権を移動せずに値を借用できます。</p>
<pre><code class="language-rust">fn length(text: &amp;str) -&gt; usize {
    text.len()
}

let message = String::from("hello");
let size = length(&amp;message);
println!("{message}: {size}");
</code></pre>
<p>借用の主な規則は次のとおりです。</p>
<ul>
<li>任意の数の不変参照 <code>&amp;T</code>、または1つの可変参照 <code>&amp;mut T</code> を作れる</li>
<li>同じ値に対する不変参照と可変参照を同時に有効にはできない</li>
<li>参照は常に有効な値を指す必要がある</li>
</ul>
<pre><code class="language-rust">fn append_world(text: &amp;mut String) {
    text.push_str(", world");
}

let mut message = String::from("hello");
append_world(&amp;mut message);
println!("{message}");
</code></pre>
<h3>スライス</h3>
<p>スライスはコレクション内の連続した範囲を借用します。データそのものは所有しません。</p>
<pre><code class="language-rust">let numbers = [10, 20, 30, 40];
let middle: &amp;[i32] = &amp;numbers[1..3];
assert_eq!(middle, &amp;[20, 30]);

let text = String::from("hello world");
let hello: &amp;str = &amp;text[..5];
assert_eq!(hello, "hello");
</code></pre>
<p>文字列の範囲指定はUTF-8の文字境界でなければpanicします。文字単位の処理には <code>chars</code>、バイト単位には <code>bytes</code> を使います。</p>
<pre><code class="language-rust">let text = "日本語";
let characters: Vec&lt;char&gt; = text.chars().collect();
assert_eq!(characters, vec!['日', '本', '語']);
assert_eq!(text.len(), 9);         // UTF-8のバイト数
assert_eq!(text.chars().count(), 3); // Unicodeスカラー値の数
</code></pre>
<h3>ライフタイムの概要</h3>
<p>ライフタイムは参照が有効な範囲を表します。多くの場合はコンパイラが推論します。</p>
<pre><code class="language-rust">fn longest&lt;'a&gt;(x: &amp;'a str, y: &amp;'a str) -&gt; &amp;'a str {
    if x.len() &gt;= y.len() { x } else { y }
}
</code></pre>
<p><code>'a</code> は返される参照が、入力参照のうち短い方の有効期間を超えないことを示します。値の寿命を延ばす指定ではありません。</p>
<p><code>'static</code> はプログラム全体にわたって有効なライフタイムです。文字列リテラルは <code>&amp;'static str</code> です。</p>
<hr />
<h2>制御構文</h2>
<h3>if・if let・let else</h3>
<p>Rustの <code>if</code> は式なので値を返せます。条件式は必ず <code>bool</code> です。</p>
<pre><code class="language-rust">let score = 80;
let grade = if score &gt;= 80 { "A" } else { "B" };

let name = Some("Ferris");
if let Some(value) = name {
    println!("{value}");
}

fn print_name(name: Option&lt;&amp;str&gt;) {
    let Some(name) = name else {
        println!("名前がありません");
        return;
    };
    println!("{name}");
}
</code></pre>
<h3>loop・while・for</h3>
<pre><code class="language-rust">// 無限ループ。breakで値を返せる
let mut count = 0;
let result = loop {
    count += 1;
    if count == 3 {
        break count * 10;
    }
};
assert_eq!(result, 30);

// while
while count &gt; 0 {
    count -= 1;
}

// for
for value in [10, 20, 30] {
    println!("{value}");
}

for number in 1..=3 {
    println!("{number}");
}

// continue：現在の反復の残りを飛ばす
for number in 1..=5 {
    if number % 2 == 0 {
        continue;
    }
    println!("odd: {number}");
}
</code></pre>
<p><code>for</code> では <code>into_iter</code> が呼び出されます。コレクションを値で渡すと所有権が移動する場合があります。</p>
<pre><code class="language-rust">let mut names = vec![String::from("Alice"), String::from("Bob")];

for name in &amp;names {        // iter(): &amp;String
    println!("{name}");
}
for name in &amp;mut names {     // iter_mut(): &amp;mut String
    name.push('!');
}
assert_eq!(names, vec!["Alice!", "Bob!"]);

// for name in names { }    // into_iter(): String。namesを消費
</code></pre>
<h3>ループラベル</h3>
<pre><code class="language-rust">'outer: for x in 0..3 {
    for y in 0..3 {
        if x + y == 3 {
            break 'outer;
        }
    }
}
</code></pre>
<h3>match</h3>
<p><code>match</code> はすべてのパターンを網羅する必要があります。</p>
<pre><code class="language-rust">let number = 7;

let description = match number {
    0 =&gt; "zero",
    1..=9 =&gt; "one digit",
    n if n % 2 == 0 =&gt; "even",
    _ =&gt; "other",
};

println!("{description}");
</code></pre>
<pre><code class="language-rust">let point = (0, 5);
match point {
    (0, y) =&gt; println!("y軸上: {y}"),
    (x, 0) =&gt; println!("x軸上: {x}"),
    (x, y) =&gt; println!("({x}, {y})"),
}
</code></pre>
<hr />
<h2>関数・クロージャ</h2>
<h3>関数</h3>
<p>引数と戻り値の型は明示します。最後の式に <code>;</code> を付けなければ、その値が返されます。</p>
<pre><code class="language-rust">fn add(left: i32, right: i32) -&gt; i32 {
    left + right
}

fn divide(left: f64, right: f64) -&gt; Option&lt;f64&gt; {
    if right == 0.0 {
        return None;
    }
    Some(left / right)
}
</code></pre>
<p>文と式の違いに注意します。</p>
<pre><code class="language-rust">let value = {
    let base = 10; // 文
    base * 2       // 式
};
assert_eq!(value, 20);
</code></pre>
<h3>クロージャ</h3>
<p>クロージャは周囲の変数を借用または取得できます。引数・戻り値の型は多くの場合推論されます。</p>
<pre><code class="language-rust">let offset = 10;
let add_offset = |value: i32| value + offset;
assert_eq!(add_offset(5), 15);

let mut values = vec![3, 1, 2];
values.sort_by_key(|value| *value);
</code></pre>
<p><code>move</code> を付けると、使用する値の所有権をクロージャへ移動します。スレッドに渡すときによく使います。</p>
<pre><code class="language-rust">let message = String::from("hello");
let show = move || println!("{message}");
show();
</code></pre>
<p>クロージャは使用方法に応じて <code>Fn</code>、<code>FnMut</code>、<code>FnOnce</code> のトレイトを実装します。</p>
<pre><code class="language-rust">fn apply_twice&lt;F&gt;(mut operation: F, value: i32) -&gt; i32
where
    F: FnMut(i32) -&gt; i32,
{
    let once = operation(value);
    operation(once)
}

assert_eq!(apply_twice(|x| x + 1, 10), 12);
</code></pre>
<h3>関数ポインタ</h3>
<p>環境をキャプチャしない関数やクロージャは <code>fn</code> 型として扱えます。</p>
<pre><code class="language-rust">fn double(value: i32) -&gt; i32 {
    value * 2
}

fn calculate(operation: fn(i32) -&gt; i32, value: i32) -&gt; i32 {
    operation(value)
}

assert_eq!(calculate(double, 5), 10);
</code></pre>
<hr />
<h2>構造体・共用体・列挙型・パターン</h2>
<h3>構造体</h3>
<pre><code class="language-rust">#[derive(Debug, Clone, PartialEq)]
struct User {
    name: String,
    age: u32,
    active: bool,
}

let name = String::from("Ferris");
let user = User {
    name,
    age: 10,
    active: true,
};

let updated = User {
    age: 11,
    ..user.clone()
};

println!("{updated:?}");
</code></pre>
<p><code>#[derive(...)]</code> で標準トレイトの実装を自動生成できます。</p>
<table>
<thead>
<tr>
<th>トレイト</th>
<th>用途</th>
</tr>
</thead>
<tbody><tr>
<td><code>Debug</code></td>
<td><code>{:?}</code> / <code>{:#?}</code> によるデバッグ表示</td>
</tr>
<tr>
<td><code>Clone</code></td>
<td>明示的な複製</td>
</tr>
<tr>
<td><code>Copy</code></td>
<td>代入時の暗黙コピー。<code>Drop</code> を実装する型には付けられない</td>
</tr>
<tr>
<td><code>PartialEq</code>, <code>Eq</code></td>
<td>等価比較</td>
</tr>
<tr>
<td><code>PartialOrd</code>, <code>Ord</code></td>
<td>順序比較</td>
</tr>
<tr>
<td><code>Hash</code></td>
<td><code>HashMap</code> / <code>HashSet</code> のキー</td>
</tr>
<tr>
<td><code>Default</code></td>
<td>デフォルト値の生成</td>
</tr>
</tbody></table>
<h3>タプル構造体・ユニット構造体</h3>
<pre><code class="language-rust">struct UserId(u64);
struct Point(i32, i32);
struct Marker;

let id = UserId(42);
let point = Point(10, 20);
println!("{} {}", id.0, point.1);
</code></pre>
<h3>共用体（union）</h3>
<p><a href="https://doc.rust-lang.org/reference/types/union.html">公式リファレンス - Union types</a></p>
<p><code>union</code> は複数のフィールドが同じメモリ領域を共有する型です。主にCとのFFIや低レベルのデータ表現で利用します。</p>
<pre><code class="language-rust">#[repr(C)]
union Number {
    integer: i32,
    floating: f32,
}

let number = Number { integer: 42 };

// SAFETY: numberはintegerフィールドで初期化している。
let integer = unsafe { number.integer };
assert_eq!(integer, 42);
</code></pre>
<p>フィールドへの書き込みは安全ですが、読み取りは格納されているビット列がそのフィールド型として有効かをコンパイラが確認できないため <code>unsafe</code> が必要です。<code>union</code> には「現在有効なフィールド」を記録する仕組みがないため、必要なら別のタグを持たせて管理します。</p>
<p>フィールド型には、破棄処理を必要としない型、参照、または <code>ManuallyDrop&lt;T&gt;</code> などの制約があります。通常のアプリケーションで複数種類の値を安全に表現する場合は、まず <code>enum</code> を検討します。</p>
<h3>メソッド・関連関数</h3>
<pre><code class="language-rust">#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    // 関連関数。Rectangle::square(10) と呼ぶ
    fn square(size: u32) -&gt; Self {
        Self {
            width: size,
            height: size,
        }
    }

    // 不変借用
    fn area(&amp;self) -&gt; u32 {
        self.width * self.height
    }

    // 可変借用
    fn resize(&amp;mut self, width: u32, height: u32) {
        self.width = width;
        self.height = height;
    }

    // 所有権を受け取る
    fn dimensions(self) -&gt; (u32, u32) {
        (self.width, self.height)
    }
}

let mut rectangle = Rectangle::square(10);
rectangle.resize(20, 30);
assert_eq!(rectangle.area(), 600);
assert_eq!(rectangle.dimensions(), (20, 30));
</code></pre>
<h3>列挙型</h3>
<p>各バリアントは異なる型・個数のデータを保持できます。</p>
<pre><code class="language-rust">#[derive(Debug)]
enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(u8, u8, u8),
}

fn handle(message: Message) {
    match message {
        Message::Quit =&gt; println!("quit"),
        Message::Move { x, y } =&gt; println!("move to {x}, {y}"),
        Message::Write(text) =&gt; println!("{text}"),
        Message::ChangeColor(r, g, b) =&gt; println!("rgb({r}, {g}, {b})"),
    }
}

handle(Message::Write(String::from("hello")));
</code></pre>
<h3>Option</h3>
<p>Rustには <code>null</code> の代わりに <code>Option&lt;T&gt;</code> があります。</p>
<pre><code class="language-rust">enum Option&lt;T&gt; {
    None,
    Some(T),
}
</code></pre>
<pre><code class="language-rust">fn find_even(values: &amp;[i32]) -&gt; Option&lt;i32&gt; {
    values.iter().copied().find(|value| value % 2 == 0)
}

let value = find_even(&amp;[1, 3, 4, 5]);
assert_eq!(value, Some(4));

// 値があるときだけ変換
let doubled = value.map(|number| number * 2);
assert_eq!(doubled, Some(8));

// デフォルト値
assert_eq!(None::&lt;i32&gt;.unwrap_or(0), 0);
</code></pre>
<p><code>unwrap</code> と <code>expect</code> は <code>None</code> でpanicします。回復可能な不在を通常の処理として扱う場合は、パターンマッチ、<code>?</code>、<code>unwrap_or</code> などを使います。</p>
<hr />
<h2>コレクション・文字列</h2>
<h3>Vec</h3>
<p><code>Vec&lt;T&gt;</code> は同じ型の値を連続したメモリ領域に保持する可変長配列です。</p>
<pre><code class="language-rust">let mut values = Vec::with_capacity(4);
values.push(10);
values.extend([20, 30]);

assert_eq!(values[0], 10);       // 範囲外はpanic
assert_eq!(values.get(1), Some(&amp;20));

for value in &amp;values {
    println!("{value}");
}

let last = values.pop();
assert_eq!(last, Some(30));
</code></pre>
<p><code>vec!</code> マクロで簡潔に生成できます。</p>
<pre><code class="language-rust">let numbers = vec![1, 2, 3];
let zeros = vec![0; 5];
</code></pre>
<h3>Stringと&amp;str</h3>
<table>
<thead>
<tr>
<th>型</th>
<th>所有権</th>
<th>主な用途</th>
</tr>
</thead>
<tbody><tr>
<td><code>String</code></td>
<td>所有する</td>
<td>可変・伸長可能なUTF-8文字列</td>
</tr>
<tr>
<td><code>&amp;str</code></td>
<td>借用する</td>
<td>文字列スライス、関数の読み取り引数</td>
</tr>
</tbody></table>
<pre><code class="language-rust">let mut message = String::from("Hello");
message.push(',');
message.push_str(" Rust");

fn greet(name: &amp;str) -&gt; String {
    format!("Hello, {name}!")
}

assert_eq!(greet(&amp;message), "Hello, Hello, Rust!");
</code></pre>
<p>複数の文字列型を読み取り専用で受け取る関数は、通常 <code>&amp;String</code> より <code>&amp;str</code> を使うと柔軟です。</p>
<pre><code class="language-rust">let first = String::from("Hello");
let second = String::from("Rust");

let joined = format!("{first}, {second}"); // 所有権を奪わない
let combined = first + ", " + &amp;second;     // firstは移動する
</code></pre>
<h3>HashMap</h3>
<pre><code class="language-rust">use std::collections::HashMap;

let mut scores = HashMap::new();
scores.insert(String::from("Alice"), 10);
scores.insert(String::from("Bob"), 20);

// 値を取得
if let Some(score) = scores.get("Alice") {
    println!("{score}");
}

// キーがない場合だけ追加
scores.entry(String::from("Carol")).or_insert(0);

// 既存値を更新
*scores.entry(String::from("Alice")).or_insert(0) += 5;

for (name, score) in &amp;scores {
    println!("{name}: {score}");
}
</code></pre>
<p><code>HashMap</code> の反復順序には依存しないでください。順序が必要なら <code>BTreeMap</code> を使います。</p>
<h3>HashSet・BTreeMap・VecDeque</h3>
<pre><code class="language-rust">use std::collections::{BTreeMap, HashSet, VecDeque};

let unique: HashSet&lt;_&gt; = [1, 2, 2, 3].into_iter().collect();
assert_eq!(unique.len(), 3);

let mut sorted = BTreeMap::new();
sorted.insert("b", 2);
sorted.insert("a", 1); // キー順に反復できる

let mut queue = VecDeque::new();
queue.push_back("first");
queue.push_back("second");
assert_eq!(queue.pop_front(), Some("first"));
</code></pre>
<hr />
<h2>エラーハンドリング</h2>
<p><a href="https://doc.rust-lang.org/stable/book/ch09-00-error-handling.html">The Rust Programming Language - エラーハンドリング</a></p>
<p>Rustでは、回復可能なエラーに <code>Result&lt;T, E&gt;</code>、回復不能なバグに <code>panic!</code> を使います。</p>
<h3>Result</h3>
<pre><code class="language-rust">enum Result&lt;T, E&gt; {
    Ok(T),
    Err(E),
}
</code></pre>
<pre><code class="language-rust">use std::fs;
use std::io;

fn read_config() -&gt; Result&lt;String, io::Error&gt; {
    match fs::read_to_string("config.toml") {
        Ok(contents) =&gt; Ok(contents),
        Err(error) =&gt; Err(error),
    }
}
</code></pre>
<h3>?演算子</h3>
<p><code>?</code> は成功値を取り出し、エラーなら呼び出し元へ早期リターンします。必要なら <code>From</code> によるエラー変換も行います。</p>
<pre><code class="language-rust">use std::fs;
use std::io;

fn read_config() -&gt; Result&lt;String, io::Error&gt; {
    let contents = fs::read_to_string("config.toml")?;
    Ok(contents)
}
</code></pre>
<p><code>main</code> も <code>Result</code> を返せます。</p>
<pre><code class="language-rust,no_run">use std::error::Error;
use std::fs;

fn main() -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
    let contents = fs::read_to_string("config.toml")?;
    println!("{contents}");
    Ok(())
}
</code></pre>
<p><code>Box&lt;dyn Error&gt;</code> は例を簡潔にできますが、ライブラリでは呼び出し側が分類できる具体的なエラー型を検討します。</p>
<h3>エラーの変換・追加処理</h3>
<pre><code class="language-rust">fn parse_number(text: &amp;str) -&gt; Result&lt;i32, String&gt; {
    let number = text
        .parse::&lt;i32&gt;()
        .map_err(|error| format!("整数に変換できません: {error}"))?;
    Ok(number)
}

assert_eq!(parse_number("42"), Ok(42));
</code></pre>
<p>よく使うメソッドは次のとおりです。</p>
<table>
<thead>
<tr>
<th>メソッド</th>
<th>概要</th>
</tr>
</thead>
<tbody><tr>
<td><code>map</code></td>
<td><code>Ok</code> の値を変換</td>
</tr>
<tr>
<td><code>map_err</code></td>
<td><code>Err</code> の値を変換</td>
</tr>
<tr>
<td><code>and_then</code></td>
<td>成功時に別の <code>Result</code> を返す処理を連結</td>
</tr>
<tr>
<td><code>unwrap_or</code></td>
<td>エラー時の値を指定</td>
</tr>
<tr>
<td><code>unwrap_or_else</code></td>
<td>エラー時の値をクロージャで生成</td>
</tr>
<tr>
<td><code>inspect</code> / <code>inspect_err</code></td>
<td>値を変更せず副作用を実行</td>
</tr>
</tbody></table>
<h3>カスタムエラー</h3>
<p>標準ライブラリだけで実装する例です。</p>
<pre><code class="language-rust">use std::error::Error;
use std::fmt;

#[derive(Debug)]
enum ParseUserError {
    EmptyName,
    InvalidAge(std::num::ParseIntError),
}

impl fmt::Display for ParseUserError {
    fn fmt(&amp;self, formatter: &amp;mut fmt::Formatter&lt;'_&gt;) -&gt; fmt::Result {
        match self {
            Self::EmptyName =&gt; write!(formatter, "名前が空です"),
            Self::InvalidAge(error) =&gt; write!(formatter, "年齢が不正です: {error}"),
        }
    }
}

impl Error for ParseUserError {
    fn source(&amp;self) -&gt; Option&lt;&amp;(dyn Error + 'static)&gt; {
        match self {
            Self::InvalidAge(error) =&gt; Some(error),
            Self::EmptyName =&gt; None,
        }
    }
}

impl From&lt;std::num::ParseIntError&gt; for ParseUserError {
    fn from(error: std::num::ParseIntError) -&gt; Self {
        Self::InvalidAge(error)
    }
}
</code></pre>
<p>アプリケーションや大規模なエラー型では、要件に応じて <code>thiserror</code> や <code>anyhow</code> などの外部crateも検討できます。</p>
<h3>panic</h3>
<pre><code class="language-rust,no_run">panic!("継続できない状態です");

let value = Some(42).expect("値が存在する前提");
assert_eq!(value, 42);
</code></pre>
<p><code>unwrap</code> / <code>expect</code> は、テスト、サンプル、または失敗がプログラムの不変条件違反を意味する箇所に限定すると意図が明確です。通常の入力エラーには <code>Result</code> / <code>Option</code> を使います。</p>
<hr />
<h2>ジェネリクス・トレイト・ライフタイム</h2>
<h3>ジェネリクス</h3>
<pre><code class="language-rust">fn largest&lt;T: PartialOrd&gt;(values: &amp;[T]) -&gt; Option&lt;&amp;T&gt; {
    let mut iterator = values.iter();
    let mut largest = iterator.next()?;

    for value in iterator {
        if value &gt; largest {
            largest = value;
        }
    }
    Some(largest)
}

assert_eq!(largest(&amp;[3, 1, 4, 2]), Some(&amp;4));
</code></pre>
<pre><code class="language-rust">#[derive(Debug)]
struct Point&lt;T&gt; {
    x: T,
    y: T,
}

impl&lt;T&gt; Point&lt;T&gt; {
    fn x(&amp;self) -&gt; &amp;T {
        &amp;self.x
    }
}
</code></pre>
<h3>トレイト</h3>
<p>トレイトは複数の型が共有する振る舞いを定義します。</p>
<pre><code class="language-rust">trait Summary {
    fn summarize(&amp;self) -&gt; String;

    fn category(&amp;self) -&gt; &amp;'static str {
        "general"
    }
}

struct Article {
    title: String,
}

impl Summary for Article {
    fn summarize(&amp;self) -&gt; String {
        self.title.clone()
    }
}
</code></pre>
<h3>トレイト境界</h3>
<pre><code class="language-rust">use std::fmt::{Debug, Display};

// impl Trait構文
fn print_summary(item: &amp;impl Display) {
    println!("{item}");
}

// トレイト境界構文
fn print_debug&lt;T: Debug&gt;(item: &amp;T) {
    println!("{item:?}");
}

// 複数の境界とwhere句
fn compare_and_print&lt;T, U&gt;(left: &amp;T, right: &amp;U)
where
    T: Display + PartialOrd&lt;U&gt;,
    U: Display,
{
    println!("{left} / {right}");
}
</code></pre>
<h3>関連型</h3>
<p>関連型はトレイト実装ごとに具体型を1つ定めます。</p>
<pre><code class="language-rust">trait Repository {
    type Item;
    type Error;

    fn find(&amp;self, id: u64) -&gt; Result&lt;Option&lt;Self::Item&gt;, Self::Error&gt;;
}
</code></pre>
<p>標準ライブラリの <code>Iterator</code> も <code>type Item</code> という関連型を持ちます。</p>
<h3>静的ディスパッチと動的ディスパッチ</h3>
<pre><code class="language-rust">use std::fmt::Display;

// コンパイル時に具体型が決まる。単相化される
fn static_dispatch(value: &amp;impl Display) {
    println!("{value}");
}

// 実行時にvtable経由で呼び出す
fn dynamic_dispatch(value: &amp;dyn Display) {
    println!("{value}");
}
</code></pre>
<p>異なる具体型を同じコレクションに入れる場合はトレイトオブジェクトを使えます。</p>
<pre><code class="language-rust">use std::fmt::Display;

let values: Vec&lt;Box&lt;dyn Display&gt;&gt; = vec![
    Box::new(42),
    Box::new(String::from("hello")),
];
</code></pre>
<h3>ライフタイム注釈</h3>
<pre><code class="language-rust">struct Excerpt&lt;'a&gt; {
    text: &amp;'a str,
}

impl&lt;'a&gt; Excerpt&lt;'a&gt; {
    fn text(&amp;self) -&gt; &amp;str {
        self.text
    }
}
</code></pre>
<p>所有する <code>String</code> を構造体に持たせれば、構造体のライフタイム注釈が不要になることがあります。借用が本当に必要かも含めて設計します。</p>
<hr />
<h2>イテレータ</h2>
<p>イテレータは遅延評価されます。<code>map</code> や <code>filter</code> などのアダプタだけでは処理されず、<code>collect</code> や <code>sum</code> などの消費アダプタで評価されます。</p>
<pre><code class="language-rust">let result: Vec&lt;i32&gt; = (1..=10)
    .filter(|number| number % 2 == 0)
    .map(|number| number * number)
    .collect();

assert_eq!(result, vec![4, 16, 36, 64, 100]);
</code></pre>
<h3>よく使うアダプタ</h3>
<pre><code class="language-rust">let values = [10, 20, 30];

let indexed: Vec&lt;_&gt; = values.iter().enumerate().collect();
let total: i32 = values.iter().sum();
let found = values.iter().find(|&amp;&amp;value| value &gt;= 20);
let all_positive = values.iter().all(|value| *value &gt; 0);
let first_two: Vec&lt;_&gt; = values.iter().take(2).copied().collect();

assert_eq!(total, 60);
assert_eq!(found, Some(&amp;20));
assert!(all_positive);
assert_eq!(first_two, vec![10, 20]);
</code></pre>
<h3>iter・iter_mut・into_iter</h3>
<table>
<thead>
<tr>
<th>呼び出し</th>
<th>要素</th>
<th>コレクション</th>
</tr>
</thead>
<tbody><tr>
<td><code>iter()</code></td>
<td><code>&amp;T</code></td>
<td>借用する</td>
</tr>
<tr>
<td><code>iter_mut()</code></td>
<td><code>&amp;mut T</code></td>
<td>可変借用する</td>
</tr>
<tr>
<td><code>into_iter()</code></td>
<td>通常 <code>T</code></td>
<td>消費する</td>
</tr>
</tbody></table>
<pre><code class="language-rust">let mut values = vec![1, 2, 3];

for value in values.iter_mut() {
    *value *= 2;
}
assert_eq!(values, vec![2, 4, 6]);

let total: i32 = values.into_iter().sum();
// valuesはここでは使用できない
assert_eq!(total, 12);
</code></pre>
<h3>独自イテレータ</h3>
<pre><code class="language-rust">struct Counter {
    current: u32,
    end: u32,
}

impl Iterator for Counter {
    type Item = u32;

    fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {
        if self.current &gt;= self.end {
            return None;
        }
        self.current += 1;
        Some(self.current)
    }
}

let values: Vec&lt;_&gt; = Counter { current: 0, end: 3 }.collect();
assert_eq!(values, vec![1, 2, 3]);
</code></pre>
<hr />
<h2>スマートポインタ</h2>
<h3>Box</h3>
<p><code>Box&lt;T&gt;</code> は値をヒープに配置し、単一の所有権を持ちます。再帰型や大きな値の移動コストを一定にしたい場合などに使います。</p>
<pre><code class="language-rust">enum List {
    Cons(i32, Box&lt;List&gt;),
    Nil,
}

let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
</code></pre>
<h3>Rc・Arc</h3>
<ul>
<li><code>Rc&lt;T&gt;</code>：単一スレッド内の参照カウント共有所有権</li>
<li><code>Arc&lt;T&gt;</code>：複数スレッド間で使えるアトミック参照カウント共有所有権</li>
<li>どちらもデフォルトでは内部の値を変更できない</li>
</ul>
<pre><code class="language-rust">use std::rc::Rc;

let shared = Rc::new(String::from("shared"));
let first = Rc::clone(&amp;shared);
let second = Rc::clone(&amp;shared);

assert_eq!(Rc::strong_count(&amp;shared), 3);
assert_eq!(first.as_str(), second.as_str());
</code></pre>
<h3>Cell・RefCell</h3>
<p>外側が不変でも内部を変更できる「内部可変性」を提供します。</p>
<pre><code class="language-rust">use std::cell::RefCell;

let values = RefCell::new(vec![1, 2]);
values.borrow_mut().push(3);
assert_eq!(*values.borrow(), vec![1, 2, 3]);
</code></pre>
<p><code>RefCell&lt;T&gt;</code> は借用規則を実行時に検査し、違反するとpanicします。スレッドセーフではありません。</p>
<h3>Drop</h3>
<pre><code class="language-rust">struct Connection;

impl Drop for Connection {
    fn drop(&amp;mut self) {
        println!("接続を閉じます");
    }
}

let connection = Connection;
drop(connection); // スコープ末尾より前に明示的に破棄
</code></pre>
<p>RustではRAIIにより、値が破棄されるとロックやファイルなどのリソースも解放されます。</p>
<hr />
<h2>モジュール・パッケージ・可視性</h2>
<p>Cargoの用語は次のとおりです。</p>
<table>
<thead>
<tr>
<th>用語</th>
<th>概要</th>
</tr>
</thead>
<tbody><tr>
<td>package</td>
<td><code>Cargo.toml</code> が定義する1つ以上のcrate</td>
</tr>
<tr>
<td>crate</td>
<td>コンパイル単位。バイナリcrateまたはライブラリcrate</td>
</tr>
<tr>
<td>module</td>
<td>crate内の名前空間・可視性を構成する単位</td>
</tr>
</tbody></table>
<h3>モジュール</h3>
<pre><code class="language-rust">mod network {
    pub mod client {
        pub fn connect() {
            println!("connected");
        }
    }

    fn private_helper() {}
}

use network::client;

fn main() {
    client::connect();
}
</code></pre>
<p>項目はデフォルトで非公開です。</p>
<table>
<thead>
<tr>
<th>指定</th>
<th>可視範囲</th>
</tr>
</thead>
<tbody><tr>
<td><code>pub</code></td>
<td>外部から公開</td>
</tr>
<tr>
<td><code>pub(crate)</code></td>
<td>同じcrate内</td>
</tr>
<tr>
<td><code>pub(super)</code></td>
<td>親モジュール内</td>
</tr>
<tr>
<td><code>pub(in path)</code></td>
<td>指定した祖先モジュール内</td>
</tr>
</tbody></table>
<h3>ファイル構成</h3>
<pre><code class="language-text">src/
├── main.rs          # バイナリcrateのルート
├── lib.rs           # ライブラリcrateのルート
├── config.rs        # mod config;
└── network/
    ├── mod.rs       # mod network; の従来形式
    └── client.rs
</code></pre>
<p>現在は <code>network.rs</code> と <code>network/client.rs</code> を組み合わせる構成も利用できます。</p>
<h3>use・as・再公開</h3>
<pre><code class="language-rust">use std::collections::HashMap;
use std::fmt::{self, Display};
use std::io::Result as IoResult;

mod models {
    pub struct User;
}

pub use models::User; // crateルートでは外部へ再公開
</code></pre>
<hr />
<h2>並行処理</h2>
<p><a href="https://doc.rust-lang.org/stable/book/ch16-00-concurrency.html">The Rust Programming Language - 並行処理</a></p>
<p>Rustでは所有権と <code>Send</code> / <code>Sync</code> トレイトにより、多くの並行処理上の誤りをコンパイル時に防ぎます。</p>
<h3>スレッド</h3>
<pre><code class="language-rust">use std::thread;

let values = vec![1, 2, 3];

let handle = thread::spawn(move || {
    let total: i32 = values.iter().sum();
    total
});

let total = handle.join().expect("スレッドがpanicしました");
assert_eq!(total, 6);
</code></pre>
<p>スコープ付きスレッドなら、現在のスコープの値を所有権移動なしで借用できます。</p>
<pre><code class="language-rust">use std::thread;

let values = vec![1, 2, 3];
thread::scope(|scope| {
    scope.spawn(|| println!("{values:?}"));
});
</code></pre>
<h3>チャネル</h3>
<p>標準の <code>mpsc</code> チャネルは複数送信者・単一受信者です。</p>
<pre><code class="language-rust">use std::sync::mpsc;
use std::thread;

let (sender, receiver) = mpsc::channel();

for id in 0..2 {
    let sender = sender.clone();
    thread::spawn(move || {
        sender.send(format!("worker {id}")).unwrap();
    });
}
drop(sender); // 元の送信側を閉じる

for message in receiver {
    println!("{message}");
}
</code></pre>
<h3>Arc&lt;Mutex&gt;</h3>
<p>複数スレッドで可変状態を共有する代表的な組み合わせです。</p>
<pre><code class="language-rust">use std::sync::{Arc, Mutex};
use std::thread;

let counter = Arc::new(Mutex::new(0));
let mut handles = Vec::new();

for _ in 0..10 {
    let counter = Arc::clone(&amp;counter);
    handles.push(thread::spawn(move || {
        let mut value = counter.lock().expect("mutexがpoisonされました");
        *value += 1;
    }));
}

for handle in handles {
    handle.join().unwrap();
}

assert_eq!(*counter.lock().unwrap(), 10);
</code></pre>
<p>ロックガードはスコープを抜けると自動的に解放されます。複数ロックを使う場合は取得順序を統一し、ロック保持時間を短くします。</p>
<h3>Send・Sync</h3>
<ul>
<li><code>Send</code>：値の所有権を別スレッドへ移動できる</li>
<li><code>Sync</code>：<code>&amp;T</code> を複数スレッド間で安全に共有できる</li>
</ul>
<p>これらはマーカートレイトで、多くの型には構成要素に基づいて自動実装されます。手動の <code>unsafe impl</code> は安全性の不変条件を実装者が保証できる場合に限ります。</p>
<h3>async / await</h3>
<p>Rustの標準ライブラリは <code>Future</code> と構文を提供しますが、汎用の非同期ランタイムは提供しません。実際のI/O処理ではTokioなどのランタイムを用途に応じて選びます。</p>
<pre><code class="language-rust">async fn fetch_value() -&gt; u32 {
    42
}

async fn calculate() -&gt; u32 {
    let value = fetch_value().await;
    value * 2
}
</code></pre>
<p><code>async fn</code> の呼び出しは遅延評価される <code>Future</code> を返します。<code>.await</code> するかランタイム上で実行するまで処理は進みません。</p>
<hr />
<h2>マクロ・属性</h2>
<h3>よく使うマクロ</h3>
<pre><code class="language-rust,no_run">let name = "Ferris";
let error = "接続に失敗しました";

println!("name={name}");
eprintln!("error: {error}");

let message = format!("id={}", 42);
let values = vec![1, 2, 3];

assert!(values.contains(&amp;2));
assert_eq!(values.len(), 3);
assert_ne!(message, "");

todo!("未実装");
unreachable!("この分岐には到達しない前提");
</code></pre>
<p><code>todo!</code>、<code>unimplemented!</code>、<code>unreachable!</code> は実行されるとpanicします。</p>
<h3>宣言的マクロ</h3>
<pre><code class="language-rust">macro_rules! hash_map {
    ($($key:expr =&gt; $value:expr),* $(,)?) =&gt; {{
        let mut map = std::collections::HashMap::new();
        $(map.insert($key, $value);)*
        map
    }};
}

let scores = hash_map! {
    "Alice" =&gt; 10,
    "Bob" =&gt; 20,
};
</code></pre>
<p>手続き的マクロにはカスタムderive、属性マクロ、関数形式マクロがあり、別の <code>proc-macro</code> crateとして定義します。</p>
<h3>よく使う属性</h3>
<pre><code class="language-rust">#[derive(Debug, Clone, PartialEq)]
struct User;

#[cfg(target_os = "linux")]
fn platform_name() -&gt; &amp;'static str {
    "Linux"
}

#[must_use]
fn calculate() -&gt; i32 {
    42
}
</code></pre>
<p>条件付きコンパイルはCargo featureにも利用できます。</p>
<pre><code class="language-rust">#[cfg(feature = "json")]
mod json_support;
</code></pre>
<hr />
<h2>テスト</h2>
<p><a href="https://doc.rust-lang.org/cargo/commands/cargo-test.html">Cargo Book - cargo test</a></p>
<h3>ユニットテスト</h3>
<pre><code class="language-rust">pub fn add(left: i32, right: i32) -&gt; i32 {
    left + right
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn adds_two_numbers() {
        assert_eq!(add(2, 3), 5);
    }

    #[test]
    #[should_panic(expected = "範囲外")]
    fn panics_when_out_of_range() {
        panic!("範囲外です");
    }

    #[test]
    #[ignore = "外部サービスが必要"]
    fn integration_like_test() {}
}
</code></pre>
<h3>Resultを返すテスト</h3>
<pre><code class="language-rust">#[test]
fn parses_number() -&gt; Result&lt;(), Box&lt;dyn std::error::Error&gt;&gt; {
    let value: i32 = "42".parse()?;
    assert_eq!(value, 42);
    Ok(())
}
</code></pre>
<h3>統合テスト</h3>
<p><code>tests/</code> 配下の各ファイルは別のcrateとしてコンパイルされ、ライブラリの公開APIをテストします。</p>
<pre><code class="language-text">src/lib.rs
tests/api_test.rs
</code></pre>
<pre><code class="language-rust,ignore">// tests/api_test.rs
use my_crate::add;

#[test]
fn public_api_adds_numbers() {
    assert_eq!(add(2, 3), 5);
}
</code></pre>
<h3>ドキュメントテスト</h3>
<pre><code class="language-rust">/// 2つの整数を加算します。
///
/// # Examples
///
/// ```
/// let result = my_crate::add(2, 3);
/// assert_eq!(result, 5);
/// ```
pub fn add(left: i32, right: i32) -&gt; i32 {
    left + right
}
</code></pre>
<p><code>cargo test</code> は通常のテストに加えてドキュメントテストも実行します。</p>
<h3>テストコマンド</h3>
<pre><code class="language-bash">cargo test                    # すべてのテスト
cargo test add                # 名前で絞り込み
cargo test -- --nocapture     # 標準出力を表示
cargo test -- --ignored       # ignoreされたテスト
cargo test --doc              # ドキュメントテストのみ
cargo test --all-features     # 全featureを有効化
</code></pre>
<hr />
<h2>標準ライブラリ早引き</h2>
<h3>表示・フォーマット</h3>
<pre><code class="language-rust">let name = "Ferris";
let age = 10;

println!("{name} is {age}");
println!("debug: {:?}", vec![1, 2, 3]);
println!("pretty: {:#?}", vec![1, 2, 3]);
println!("hex: {age:x}, binary: {age:b}");
println!("right: {:&gt;8}", name);
println!("zero pad: {age:04}");
</code></pre>
<h3>文字列処理</h3>
<pre><code class="language-rust">let text = "  Hello, Rust  ";

assert_eq!(text.trim(), "Hello, Rust");
assert!(text.contains("Rust"));
assert!(text.trim().starts_with("Hello"));
assert_eq!(text.replace("Rust", "World"), "  Hello, World  ");

let parts: Vec&lt;_&gt; = "a,b,c".split(',').collect();
assert_eq!(parts, vec!["a", "b", "c"]);

let joined = ["a", "b", "c"].join("-");
assert_eq!(joined, "a-b-c");
</code></pre>
<h3>数値変換</h3>
<pre><code class="language-rust">fn main() -&gt; Result&lt;(), Box&lt;dyn std::error::Error&gt;&gt; {
    let number: i32 = "42".parse()?;
    let hex = i32::from_str_radix("ff", 16)?;
    let text = number.to_string();

    assert_eq!(hex, 255);
    assert_eq!(text, "42");
    Ok(())
}
</code></pre>
<h3>ファイル・パス</h3>
<pre><code class="language-rust,no_run">use std::fs;
use std::io;
use std::path::{Path, PathBuf};

fn copy_file() -&gt; io::Result&lt;()&gt; {
    let path = Path::new("data").join("input.txt");
    let contents = fs::read_to_string(&amp;path)?;
    fs::write("output.txt", contents)?;

    let mut buffer = PathBuf::from("data");
    buffer.push("output.json");
    Ok(())
}
</code></pre>
<p>大きなファイルは全体をメモリに読み込まず、<code>BufReader</code> で逐次処理できます。</p>
<pre><code class="language-rust">use std::fs::File;
use std::io::{self, BufRead, BufReader};

fn print_lines(path: &amp;str) -&gt; io::Result&lt;()&gt; {
    let file = File::open(path)?;
    for line in BufReader::new(file).lines() {
        println!("{}", line?);
    }
    Ok(())
}
</code></pre>
<h3>環境変数・コマンドライン引数</h3>
<pre><code class="language-rust">use std::env;

let args: Vec&lt;String&gt; = env::args().collect();

match env::var("APP_ENV") {
    Ok(value) =&gt; println!("APP_ENV={value}"),
    Err(env::VarError::NotPresent) =&gt; println!("未設定"),
    Err(env::VarError::NotUnicode(_)) =&gt; println!("Unicodeではありません"),
}
</code></pre>
<p>シークレットをログやエラーメッセージに出力しないよう注意します。</p>
<h3>時間</h3>
<pre><code class="language-rust">use std::thread;
use std::time::{Duration, Instant, SystemTime};

let started = Instant::now();
thread::sleep(Duration::from_millis(10));
println!("elapsed={:?}", started.elapsed());

let now = SystemTime::now();
</code></pre>
<p>標準ライブラリは日時の書式化やタイムゾーン処理を広範には提供しません。必要な場合は要件に合う外部crateを選びます。</p>
<h3>OnceLock・LazyLock</h3>
<pre><code class="language-rust">use std::sync::{LazyLock, OnceLock};

static CONFIG: OnceLock&lt;String&gt; = OnceLock::new();
static DEFAULTS: LazyLock&lt;Vec&lt;String&gt;&gt; =
    LazyLock::new(|| vec![String::from("default")]);

let config = CONFIG.get_or_init(|| String::from("production"));
assert_eq!(config, "production");
assert_eq!(DEFAULTS.len(), 1);
</code></pre>
<hr />
<h2>外部関数の呼び出し（extern・FFI）</h2>
<p><a href="https://doc.rust-lang.org/reference/items/external-blocks.html">公式リファレンス - External blocks</a></p>
<p><code>extern</code> はRust以外のABIを使う関数やstatic項目を宣言するために使います。<code>extern "C"</code> はC ABIを表します。</p>
<p>Edition 2024では、外部ブロックを <code>unsafe extern</code> として宣言する必要があります。宣言した関数のシグネチャが実際の外部関数と一致することはRustコンパイラが検証できないため、宣言者が安全性を保証します。</p>
<pre><code class="language-rust,no_run">use std::ffi::c_int;

unsafe extern "C" {
    fn abs(input: c_int) -&gt; c_int;
}

// SAFETY: Cのabsへ、有効範囲内のc_int値を渡している。
let value = unsafe { abs(-42) };
assert_eq!(value, 42);
</code></pre>
<p>Rustの関数をC ABIで外部へ公開する場合も <code>extern "C"</code> を使います。</p>
<pre><code class="language-rust">#[unsafe(no_mangle)]
pub extern "C" fn add(left: i32, right: i32) -&gt; i32 {
    left + right
}

assert_eq!(add(2, 3), 5);
</code></pre>
<p>Edition 2024では <code>no_mangle</code> はunsafe属性のため、<code>#[unsafe(no_mangle)]</code> と記述します。</p>
<p>FFI境界では次の点を明示的に確認します。</p>
<ul>
<li>ABIと関数シグネチャが外部定義と一致していること</li>
<li>共有する構造体などに必要に応じて <code>#[repr(C)]</code> を指定すること</li>
<li>ポインタのnull、有効範囲、アラインメント、ライフタイム</li>
<li>文字列のエンコーディングと終端方法</li>
<li>メモリをどちらが確保・解放するか</li>
<li>panicや外部例外をABI境界を越えて伝播させないこと</li>
</ul>
<p>外部ヘッダーから多数の宣言を取り込む場合は、手書きによる不一致を避けるため、用途に応じてbindgenなどの生成ツールも検討します。</p>
<hr />
<h2>unsafe Rust</h2>
<p><a href="https://doc.rust-lang.org/stable/book/ch20-01-unsafe-rust.html">The Rust Programming Language - unsafe Rust</a></p>
<p><code>unsafe</code> は借用検査を無効にするものではなく、安全性をコンパイラだけでは証明できない一部の操作を許可します。</p>
<p>unsafeコンテキストで可能になる主な操作は次のとおりです。</p>
<ul>
<li>生ポインタのデリファレンス</li>
<li>unsafe関数・メソッドの呼び出し</li>
<li>可変static変数へのアクセス</li>
<li>unsafeトレイトの実装</li>
<li><code>union</code> フィールドへのアクセス</li>
</ul>
<pre><code class="language-rust">unsafe fn first_unchecked(values: &amp;[i32]) -&gt; &amp;i32 {
    // SAFETY: 呼び出し側がvaluesは空でないことを保証する。
    unsafe { values.get_unchecked(0) }
}

let values = [10, 20];
// SAFETY: valuesには2要素あり、空ではない。
let first = unsafe { first_unchecked(&amp;values) };
assert_eq!(*first, 10);
</code></pre>
<p>Edition 2024では、<code>unsafe fn</code> の本体でもunsafe操作を明示的な <code>unsafe</code> ブロックに入れる必要があります。unsafeコードは範囲を小さくし、安全性の前提を <code>SAFETY</code> コメントで記録します。</p>
<p>安全なAPIとして公開する場合は、内部のすべての呼び出しに対して安全性の不変条件が成り立つよう設計・検証する必要があります。</p>
<hr />
<h2>Cargo・依存関係管理</h2>
<p><a href="https://doc.rust-lang.org/cargo/">The Cargo Book</a></p>
<h3>よく使うコマンド</h3>
<pre><code class="language-bash">cargo new app                 # 新規バイナリpackage
cargo new --lib my-library    # 新規ライブラリpackage
cargo init                    # 既存ディレクトリを初期化

cargo check                   # 高速な型チェック
cargo build                   # デバッグビルド
cargo build --release         # 最適化ビルド
cargo run -- arg1 arg2        # 実行ファイルへ引数を渡す
cargo test                    # テスト
cargo doc --open              # ドキュメント生成・表示

cargo fmt --check             # フォーマット確認
cargo clippy --all-targets --all-features -- -D warnings
</code></pre>
<p><code>cargo check</code> は最終バイナリを生成しないため、実装中の確認に適しています。リリース前は <code>cargo build</code> / <code>cargo test</code> も実行します。</p>
<h3>Cargo.toml</h3>
<pre><code class="language-toml">[package]
name = "example"
version = "0.1.0"
edition = "2024"
rust-version = "1.98"

[dependencies]

[dev-dependencies]

[features]
default = []
json = []
</code></pre>
<p><code>edition</code> と <code>rust-version</code> は別の設定です。</p>
<ul>
<li><code>edition</code>：利用する言語Editionと移行上の互換性境界</li>
<li><code>rust-version</code>：packageがサポートする最小Rustバージョン（MSRV）</li>
</ul>
<p>ライブラリでは、実際にサポート・CI検証する最小バージョンを <code>rust-version</code> に指定します。</p>
<h3>依存関係</h3>
<pre><code class="language-bash">cargo add serde --features derive
cargo add --dev tempfile
cargo update
cargo tree
cargo tree -d                 # 重複バージョンを確認
</code></pre>
<p><code>Cargo.lock</code> は再現可能なビルドのための正確な依存バージョンを記録します。バイナリ・アプリケーションでは通常コミットします。ライブラリでもワークスペースやCIの再現性のためコミットできますが、利用者が解決する依存バージョンは <code>Cargo.toml</code> の制約に従います。</p>
<h3>feature</h3>
<pre><code class="language-toml">[features]
default = []
json = ["dep:serde", "dep:serde_json"]

[dependencies]
serde = { version = "1", features = ["derive"], optional = true }
serde_json = { version = "1", optional = true }
</code></pre>
<pre><code class="language-bash">cargo build --features json
cargo test --all-features
cargo test --no-default-features
</code></pre>
<p>featureは加算的に設計することが推奨されます。同じfeature名を無効化の意味に使うと、依存グラフ上で組み合わされたときに予期しない動作になりやすくなります。</p>
<h3>ワークスペース</h3>
<pre><code class="language-toml">[workspace]
resolver = "3"
members = ["crates/core", "crates/cli"]

[workspace.package]
edition = "2024"
rust-version = "1.98"

[workspace.dependencies]
serde = { version = "1", features = ["derive"] }
</code></pre>
<pre><code class="language-toml"># crates/core/Cargo.toml
[package]
name = "example-core"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true

[dependencies]
serde.workspace = true
</code></pre>
<hr />
<h2>Tips &amp; よくあるミス</h2>
<h3>不要なclone</h3>
<p>借用で十分な箇所に <code>clone</code> を追加すると、所有権エラーは消えても余分な割り当てやコピーが発生します。</p>
<pre><code class="language-rust">fn print_name(name: &amp;str) {
    println!("{name}");
}

let name = String::from("Ferris");
print_name(&amp;name); // clone不要
println!("{name}");
</code></pre>
<p>まず所有権を誰が持つべきか、関数が値を所有する必要があるかを検討します。</p>
<h3>&amp;Stringより&amp;str</h3>
<pre><code class="language-rust">fn length(text: &amp;str) -&gt; usize {
    text.len()
}

length("literal");
length(&amp;String::from("owned"));
</code></pre>
<p>読み取り専用の文字列引数は <code>&amp;str</code> にすると、文字列リテラルと <code>String</code> の両方を受け取れます。同様に、読み取り専用の可変長配列は <code>&amp;Vec&lt;T&gt;</code> より <code>&amp;[T]</code> が一般的です。</p>
<h3>インデックスアクセス</h3>
<pre><code class="language-rust">let values = vec![10, 20, 30];

// 入力に由来する添字など、範囲外になり得る場合
if let Some(value) = values.get(10) {
    println!("{value}");
}
</code></pre>
<p><code>values[index]</code> は範囲外でpanicします。不確実な添字には <code>get</code> を使います。</p>
<h3>Unicode文字列</h3>
<pre><code class="language-rust">let text = "🦀Rust";
assert_eq!(text.len(), 8); // バイト数

let first = text.chars().next();
assert_eq!(first, Some('🦀'));
</code></pre>
<p><code>String</code> / <code>str</code> は整数による直接インデックスを提供しません。書記素クラスタ（見た目上の文字）単位の処理が必要なら、Unicode仕様を扱う外部crateを検討します。</p>
<h3>Mutexガードをawaitをまたいで保持しない</h3>
<p>同期 <code>Mutex</code> のガードを <code>.await</code> の間保持すると、デッドロックやタスク停滞の原因になります。必要な値を取り出してガードを先に破棄するか、非同期ランタイム向けのMutexを要件に応じて使います。</p>
<pre><code class="language-rust">use std::sync::Mutex;

async fn async_operation(_value: String) {}

async fn process(shared: &amp;Mutex&lt;String&gt;) {
    let value = {
        let guard = shared.lock().expect("mutexがpoisonされました");
        guard.clone()
    }; // ここでガードを解放

    async_operation(value).await;
}
</code></pre>
<h3>ブロッキング処理をasyncタスクで直接実行しない</h3>
<p>CPU負荷の高い処理や同期I/Oを非同期executor上で直接実行すると、他のタスクを止めることがあります。利用するランタイムが提供するブロッキング処理用APIや専用スレッドを使います。</p>
<h3>公開APIのpanic</h3>
<p>ライブラリの公開APIでは、通常の入力でpanicせず <code>Result</code> / <code>Option</code> を返す設計を検討します。panicする条件がある場合は、ドキュメントの <code># Panics</code> セクションに記載します。</p>
<pre><code class="language-rust">/// 指定位置の値を返します。
///
/// # Panics
///
/// `index` が範囲外の場合にpanicします。
pub fn value_at(values: &amp;[i32], index: usize) -&gt; i32 {
    values[index]
}
</code></pre>
<h3>警告を放置しない</h3>
<pre><code class="language-bash">cargo fmt --check
cargo clippy --all-targets --all-features -- -D warnings
cargo test --all-features
</code></pre>
<p>Clippyの提案は有用ですが、意味や性能特性が変わらないか確認して適用します。プロジェクト固有のlint方針がある場合はそちらを優先します。</p>
<hr />
<h2>公式リファレンス</h2>
<ul>
<li><a href="https://www.rust-lang.org/ja/">Rust公式サイト</a></li>
<li><a href="https://doc.rust-lang.org/stable/book/">The Rust Programming Language</a></li>
<li><a href="https://doc.rust-lang.org/rust-by-example/">Rust By Example</a></li>
<li><a href="https://doc.rust-lang.org/reference/">The Rust Reference</a></li>
<li><a href="https://doc.rust-lang.org/std/">Rust標準ライブラリ</a></li>
<li><a href="https://doc.rust-lang.org/cargo/">The Cargo Book</a></li>
<li><a href="https://doc.rust-lang.org/clippy/">Clippy Documentation</a></li>
<li><a href="https://doc.rust-lang.org/edition-guide/">The Rust Edition Guide</a></li>
<li><a href="https://blog.rust-lang.org/2026/08/20/Rust-1.98.0/">Rust 1.98.0リリースノート</a></li>
</ul>
<hr />
<p>Rustでは、所有権・借用・型によって不正な状態を表現しにくくすることが重要です。 コンパイラのエラーは制約だけでなく、設計上の問題を早い段階で見つける手がかりとして活用できます。</p>
]]></content:encoded></item><item><title><![CDATA[Go Cheat Sheet]]></title><description><![CDATA[Go 1.27 cheat sheet with examples of syntax, slices, maps, interfaces, errors, goroutines, channels, context, generics, iterators, and testing.]]></description><link>https://nobuo-miura.hashnode.dev/go-cheat-sheet</link><guid isPermaLink="true">https://nobuo-miura.hashnode.dev/go-cheat-sheet</guid><category><![CDATA[Go Language]]></category><category><![CDATA[golang]]></category><category><![CDATA[cheatsheet]]></category><dc:creator><![CDATA[Nobuo Miura]]></dc:creator><pubDate>Fri, 27 Nov 2026 10:32:45 GMT</pubDate><content:encoded><![CDATA[<p>This cheat sheet is based on Go 1.27.</p>
<h2>Program structure</h2>
<pre><code class="language-go">package main  // Every executable must be in package main.

import (
	"fmt"
	"os"
)

func main() {
	fmt.Println("Hello, Go 1.27")
	os.Exit(0)
}
</code></pre>
<ul>
<li>Every Go source file starts with a <code>package</code> declaration.</li>
<li>An executable program uses <code>package main</code> and a <code>main</code> function.</li>
<li>Group standard-library and third-party imports separately.</li>
</ul>
<hr />
<h2>Variables, constants, and types</h2>
<h3>Variable declarations and inference</h3>
<pre><code class="language-go">// var can infer the type from an initializer.
var name = "Gopher" // string
var age int          // No initializer: specify a type. Zero value: 0.
var id int64 = 42    // Use an explicit type when int is not what you want.

// Short declaration: inside functions only.
city := "Tokyo"

// Declare multiple variables in a block.
var (
	x, y int = 1, 2
	msg  string
)
</code></pre>
<p>Use <code>var name = "Gopher"</code> when an initializer makes the type clear. Without an initializer, write the type explicitly. A <code>:=</code> declaration is only valid inside a function, and at least one name on its left side must be new.</p>
<h3>Types and zero values</h3>
<table>
<thead>
<tr>
<th>Category</th>
<th>Types</th>
<th>Zero value</th>
</tr>
</thead>
<tbody><tr>
<td>Numbers</td>
<td>integers, floats, complex numbers</td>
<td><code>0</code> (<code>0 + 0i</code> for complex)</td>
</tr>
<tr>
<td>Strings</td>
<td><code>string</code></td>
<td><code>""</code></td>
</tr>
<tr>
<td>Booleans</td>
<td><code>bool</code></td>
<td><code>false</code></td>
</tr>
<tr>
<td>Arrays</td>
<td><code>[N]T</code></td>
<td>every element is <code>T</code>'s zero value</td>
</tr>
<tr>
<td>Structs</td>
<td><code>struct</code></td>
<td>every field has its zero value</td>
</tr>
<tr>
<td>Reference-containing types</td>
<td>pointers, slices, maps, channels, functions, interfaces</td>
<td><code>nil</code></td>
</tr>
<tr>
<td>Defined types</td>
<td>e.g. <code>type UserID int</code></td>
<td>the underlying type's zero value</td>
</tr>
</tbody></table>
<table>
<thead>
<tr>
<th>Category</th>
<th>Types</th>
<th>Notes</th>
</tr>
</thead>
<tbody><tr>
<td>Boolean</td>
<td><code>bool</code></td>
<td><code>true</code> or <code>false</code></td>
</tr>
<tr>
<td>String</td>
<td><code>string</code></td>
<td>immutable sequence of bytes (usually UTF-8, but invalid UTF-8 is allowed)</td>
</tr>
<tr>
<td>Signed integers</td>
<td><code>int</code>, <code>int8</code>, <code>int16</code>, <code>int32</code>, <code>int64</code></td>
<td><code>int</code> is platform-sized (32 or 64 bit)</td>
</tr>
<tr>
<td>Unsigned integers</td>
<td><code>uint</code>, <code>uint8</code>, <code>uint16</code>, <code>uint32</code>, <code>uint64</code>, <code>uintptr</code></td>
<td><code>uintptr</code> holds a pointer's raw bits</td>
</tr>
<tr>
<td>Aliases</td>
<td><code>byte</code>, <code>rune</code></td>
<td>aliases for <code>uint8</code> and <code>int32</code></td>
</tr>
<tr>
<td>Floating point</td>
<td><code>float32</code>, <code>float64</code></td>
<td>IEEE 754</td>
</tr>
<tr>
<td>Complex</td>
<td><code>complex64</code>, <code>complex128</code></td>
<td>float32 or float64 real and imaginary parts</td>
</tr>
</tbody></table>
<pre><code class="language-go">var i8 int8 = 127             // -128 to 127
var f64 float64 = 3.141592653589793
var c complex128 = 1 + 2i

s := "こんにちは"
runes := []rune(s) // Unicode code points
bytes := []byte(s) // raw bytes

// rune = int32 alias for a Unicode code point
var ch rune = '🐹'
</code></pre>
<h3>Conversion and constants</h3>
<pre><code class="language-go">i := 42
f := float64(i)              // Conversions are always explicit; no implicit coercion.
text := fmt.Sprintf("%d", i) // Number to string.
n, err := strconv.Atoi("123") // String to number.

const Pi = 3.14159

// iota: auto-incremented integer constant.
type Weekday int

const (
	Sunday Weekday = iota // 0
	Monday                // 1
	Tuesday               // 2
)

// Bit-flag pattern.
type Permission uint

const (
	Read    Permission = 1 &lt;&lt; iota // 1
	Write                          // 2
	Execute                        // 4
)
</code></pre>
<h3>Pointers</h3>
<pre><code class="language-go">x := 10
p := &amp;x  // Take the address of x.
*p = 20  // Dereference the pointer.
fmt.Println(x) // 20

p1 := new(int) // *int; the pointed-to value is 0.

// Go 1.26+: new accepts an expression as well as a type.
// This does not compile with Go 1.25 or earlier.
p2 := new(42)               // *int; the pointed-to value is 42.
p3 := new(Person{Name: "Alice"}) // *Person initialized with a literal.
</code></pre>
<hr />
<h2>Control flow</h2>
<h3>if</h3>
<pre><code class="language-go">// An initialization statement is scoped to this if/else chain.
if err := doSomething(); err != nil {
	return fmt.Errorf("do something: %w", err)
}

if x &gt; 0 {
	fmt.Println("positive")
} else if x &lt; 0 {
	fmt.Println("negative")
} else {
	fmt.Println("zero")
}
</code></pre>
<h3>for</h3>
<pre><code class="language-go">// C-style loop.
for i := 0; i &lt; 5; i++ {
}

// Go has no while keyword; use for instead.
for n &gt; 0 {
	n--
}

// Infinite loop.
for {
	if done {
		break
	}
}

// range returns an index and a value for slices and arrays.
for i, v := range []int{10, 20, 30} {
	fmt.Println(i, v) // 0 10 / 1 20 / 2 30
}

// Discard the index.
for _, v := range slice {
}

// Strings range over Unicode code points (runes), not bytes.
for i, r := range "日本語" {
	fmt.Printf("%d: %c\n", i, r)
}

// Maps.
for k, v := range m {
	fmt.Println(k, v) // Iteration order is unspecified.
}
</code></pre>
<h3>switch</h3>
<pre><code class="language-go">// Expression switch (fallthrough requires an explicit keyword).
switch os := runtime.GOOS; os {
case "darwin":
	fmt.Println("macOS")
case "linux":
	fmt.Println("Linux")
default:
	fmt.Println("Other")
}

// Condition-less switch is a cleaner alternative to a long if-else chain.
switch {
case x &gt; 100:
	fmt.Println("big")
case x &gt; 10:
	fmt.Println("medium")
default:
	fmt.Println("small")
}

// Type switch: identify the dynamic type of an interface value.
func describe(i any) {
	switch v := i.(type) {
	case int:
		fmt.Printf("int: %d\n", v)
	case string:
		fmt.Printf("string: %q\n", v)
	default:
		fmt.Printf("unknown: %T\n", v)
	}
}
</code></pre>
<h3>defer</h3>
<p><code>defer</code> schedules a call to run just before the surrounding function returns. Use it for cleanup: closing files, response bodies, mutexes, and contexts. Deferred calls run in LIFO order.</p>
<pre><code class="language-go">func writeFile(path string) error {
	f, err := os.Create(path)
	if err != nil {
		return err
	}
	defer f.Close() // Runs when writeFile returns, regardless of how.

	defer fmt.Println("third")
	defer fmt.Println("second")
	defer fmt.Println("first")
	// Prints: first, second, third.
	return nil
}
</code></pre>
<blockquote>
<p><strong>Note</strong> Deferred call arguments are evaluated when <code>defer</code> is encountered. In a long-running loop, a deferred cleanup does not run until the function returns, so resources accumulate. Close them promptly or move the loop body into a helper function.</p>
</blockquote>
<hr />
<h2>Functions</h2>
<h3>Basic</h3>
<pre><code class="language-go">// Multiple return values.
func divide(a, b float64) (float64, error) {
	if b == 0 {
		return 0, errors.New("division by zero")
	}
	return a / b, nil
}

result, err := divide(10, 3)

// Named return values (useful as documentation for short functions).
func minMax(nums []int) (min, max int) {
	min, max = nums[0], nums[0]
	for _, n := range nums[1:] {
		if n &lt; min {
			min = n
		}
		if n &gt; max {
			max = n
		}
	}
	return // Naked return.
}
</code></pre>
<h3>Variadic functions</h3>
<pre><code class="language-go">func sum(nums ...int) int {
	total := 0
	for _, n := range nums {
		total += n
	}
	return total
}

sum(1, 2, 3)
nums := []int{1, 2, 3}
sum(nums...) // Spread a slice into variadic arguments.
</code></pre>
<h3>First-class functions and closures</h3>
<p>Functions are values in Go: you can assign them to variables, pass them as arguments, and return them. A closure captures variables from its surrounding scope and keeps them alive after the outer function returns.</p>
<pre><code class="language-go">// Assign a function to a variable.
add := func(a, b int) int { return a + b }

// Pass a function as an argument.
apply := func(f func(int, int) int, x, y int) int {
	return f(x, y)
}
fmt.Println(apply(add, 3, 4)) // 7

// This closure captures n.
func counter() func() int {
	n := 0
	return func() int {
		n++
		return n
	}
}

c := counter()
c() // 1
c() // 2
</code></pre>
<h3>init</h3>
<p>An <code>init</code> function runs automatically while a package is initialized, before <code>main</code>. A package may have more than one <code>init</code> function. Prefer explicit initialization in <code>main</code> for ordinary application setup; reserve <code>init</code> for package-level registration.</p>
<pre><code class="language-go">// Runs automatically at package initialization.
func init() {
	// Register a driver or handler.
}
</code></pre>
<hr />
<h2>Arrays, slices, and maps</h2>
<h3>Memory layout</h3>
<pre><code class="language-plaintext">Array (fixed length, value type)
┌───┬───┬───┬───┬───┐
│ 0 │ 1 │ 2 │ 3 │ 4 │  ← contiguous memory (placement decided by the compiler)
└───┴───┴───┴───┴───┘

Slice (variable-length view)
┌────────┬──────┬──────┐
│ ptr    │ len  │ cap  │  ← 3-word slice header
└────┬───┴──────┴──────┘
     ↓
┌───┬───┬───┬───┬───┬───┐
│ 0 │ 1 │ 2 │ 3 │   │   │  ← underlying array
└───┴───┴───┴───┴───┴───┘
     ↑           ↑
    len=4       cap=6

Note: actual placement (stack/heap) is decided by escape analysis.
</code></pre>
<h3>Arrays</h3>
<p>Arrays have a fixed length, and that length is part of their type: <code>[3]int</code> and <code>[4]int</code> are different types. Arrays are values, so assigning or passing one copies all its elements.</p>
<pre><code class="language-go">var a [3]int              // [0 0 0]
b := [3]int{1, 2, 3}
c := [...]int{4, 5, 6}   // Length inferred from the literal.

// Arrays are copied by value.
d := b
d[0] = 99 // b is unchanged.
</code></pre>
<h3>Slices</h3>
<p>A slice is a variable-length view over part or all of an underlying array. Unlike an array, its length is not part of its type. Assigning a slice copies only its header, so two slices may share elements.</p>
<pre><code class="language-go">// Create a slice.
s := []int{1, 2, 3}
s2 := make([]int, 5)     // len=5, cap=5
s3 := make([]int, 3, 10) // len=3, cap=10

// append may allocate a new backing array when cap is exceeded.
s = append(s, 4, 5)
s = append(s, []int{6, 7}...)

// Slicing shares the backing array.
sub := s[1:3]            // s[1] and s[2]; shares s's array.
limited := s[1:3:3]      // Third index limits the resulting cap.

// copy produces an independent slice.
clone := make([]int, len(s))
copy(clone, s)

// Delete element at index i while preserving order.
i := 2
s = append(s[:i], s[i+1:]...)

fmt.Println(len(s), cap(s))
</code></pre>
<blockquote>
<p><strong>Caution</strong> A subslice shares its backing array with the original. Mutating one can mutate the other. Use <code>copy</code> when an independent slice is required.</p>
</blockquote>
<h3>Maps</h3>
<p>Maps associate keys with values. Iteration order is unspecified. Keys must be comparable; slices, maps, and functions cannot be map keys.</p>
<pre><code class="language-go">// Create a map.
m := map[string]int{"a": 1, "b": 2}
m2 := make(map[string]int)

m["c"] = 3
delete(m, "a") // delete is a built-in function.

// Check for key existence.
v, ok := m["missing"] // ok is false when the key is absent.
if ok {
	fmt.Println(v)
}

// Iteration order is unspecified.
for k, v := range m {
	fmt.Println(k, v)
}
</code></pre>
<blockquote>
<p><strong>Caution</strong> The zero value of a map is <code>nil</code>. Reading from a nil map is safe, but writing to one panics. Initialize it with <code>make</code> or a map literal first.</p>
</blockquote>
<hr />
<h2>Structs, methods, and tags</h2>
<h3>Structs and embedding</h3>
<pre><code class="language-go">type Person struct {
	Name string // Exported: accessible from other packages.
	Age  int
	addr string // Unexported: package-private.
}

// Named-field initialization (preferred).
p1 := Person{Name: "Alice", Age: 30}
p2 := new(Person) // *Person; all fields are zero values.

// Embedding promotes fields and methods.
type Employee struct {
	Person            // Fields and methods of Person are promoted.
	Department string
}

e := Employee{Person: Person{Name: "Carol", Age: 28}, Department: "Eng"}
fmt.Println(e.Name) // Transparent access to Person.Name.

// Go 1.27+: promoted fields can be used directly as literal keys.
e2 := Employee{Name: "Eve", Age: 32, Department: "Sales"}
</code></pre>
<p>Starting with Go 1.27, a struct literal key may be any valid field selector for the struct type. Here, <code>Name</code> and <code>Age</code> are promoted from the embedded <code>Person</code> field.</p>
<h3>Methods</h3>
<pre><code class="language-go">// Value receiver: p is a copy of the caller.
func (p Person) Greet() string {
	return "Hi, I'm " + p.Name
}

// Pointer receiver: can modify the original Person.
func (p *Person) Birthday() {
	p.Age++
}

p := Person{Name: "Dave", Age: 20}
p.Birthday()       // Go automatically passes &amp;p.
fmt.Println(p.Age) // 21
</code></pre>
<blockquote>
<p><strong>When to use pointer receivers</strong></p>
<ul>
<li>The method needs to modify the receiver → pointer receiver.</li>
<li>The struct is large (avoid copy overhead) → pointer receiver.</li>
<li>Otherwise, either works.</li>
</ul>
<p>Keep receiver kinds consistent across all methods of one type.</p>
</blockquote>
<h3>Struct tags</h3>
<p>Struct tags are metadata attached to fields. The language does not interpret them; packages such as <code>encoding/json</code> and ORMs read them through reflection.</p>
<pre><code class="language-go">type User struct {
	ID    int    `json:"id" db:"user_id"`
	Email string `json:"email,omitempty"` // Omitted from JSON when empty.
}

// encoding/json reads tags through reflection.
data, _ := json.Marshal(User{ID: 1, Email: ""})
// → {"id":1}   (Email omitted by omitempty)
</code></pre>
<hr />
<h2>Interfaces</h2>
<p>An interface defines a set of methods. A type satisfies an interface implicitly — no <code>implements</code> keyword. This lets code depend on behavior rather than a concrete type.</p>
<pre><code class="language-plaintext">interface value layout (the internal representation is not part of the spec)

var s Shape = Circle{Radius: 5}

  s (interface value)
  ┌──────────────┬──────────────┐
  │  type info   │  value/ptr   │
  │  (Circle)    │  {Radius:5}  │
  └──────────────┴──────────────┘

  If either part is nil while the other is not, the interface value itself is not nil.
  (See nil interface trap in Tips.)
</code></pre>
<pre><code class="language-go">type Shape interface {
	Area() float64
	Perimeter() float64
}

type Circle struct{ Radius float64 }

func (c Circle) Area() float64      { return math.Pi * c.Radius * c.Radius }
func (c Circle) Perimeter() float64 { return 2 * math.Pi * c.Radius }

// Circle implicitly satisfies Shape.
var s Shape = Circle{Radius: 5}
fmt.Println(s.Area())
</code></pre>
<h3>Type assertions and type switches</h3>
<pre><code class="language-go">// Safe type assertion; the single-result form panics on failure.
c, ok := s.(Circle)
if ok {
	fmt.Println("radius:", c.Radius)
}

// any is an alias for interface{} (Go 1.18+).
func printAny(v any) {
	fmt.Printf("%T: %v\n", v, v)
}
</code></pre>
<h3>Small interfaces used everywhere</h3>
<pre><code class="language-go">// io.Reader and io.Writer are the most widely used interfaces in the stdlib.
type Reader interface { Read(p []byte) (n int, err error) }
type Writer interface { Write(p []byte) (n int, err error) }

// Implementing fmt.Stringer controls how fmt.Println prints a value.
type Stringer interface { String() string }

func (p Person) String() string {
	return fmt.Sprintf("%s (%d)", p.Name, p.Age)
}

fmt.Println(Person{Name: "Eve", Age: 22}) // Eve (22)
</code></pre>
<hr />
<h2>Errors</h2>
<pre><code class="language-go">// error is a built-in interface: type error interface { Error() string }

f, err := os.Open("file.txt")
if err != nil {
	return fmt.Errorf("open file: %w", err) // %w wraps err for errors.Is/As.
}
defer f.Close()
</code></pre>
<h3>Custom errors</h3>
<pre><code class="language-go">type NotFoundError struct {
	Resource string
	ID       int
}

func (e *NotFoundError) Error() string {
	return fmt.Sprintf("%s (id=%d) not found", e.Resource, e.ID)
}

func findUser(id int) (*User, error) {
	if id &lt;= 0 {
		return nil, &amp;NotFoundError{Resource: "user", ID: id}
	}
	// ...
	return nil, nil
}
</code></pre>
<h3>errors package</h3>
<pre><code class="language-go">import "errors"

// Sentinel error for errors.Is comparisons.
var ErrNotFound = errors.New("not found")

func fetchUser(id int) (*User, error) {
	if id &lt;= 0 {
		return nil, fmt.Errorf("fetchUser: %w", ErrNotFound) // Wrap with %w.
	}
	return nil, nil
}

_, err := fetchUser(-1) // fetchUser returns (*User, error); discard the value.

// errors.Is traverses the error chain to find a matching sentinel.
if errors.Is(err, ErrNotFound) {
	fmt.Println("not found")
}

// errors.As traverses the chain and extracts a value of the target type.
func findItem(id int) error {
	return fmt.Errorf("findItem: %w", &amp;NotFoundError{Resource: "item", ID: id})
}

var nfe *NotFoundError
if errors.As(findItem(42), &amp;nfe) {
	fmt.Println("resource:", nfe.Resource) // "item"
}

// Go 1.26+: a type-safe generic alternative to errors.As.
if nfe, ok := errors.AsType[*NotFoundError](findItem(42)); ok {
	fmt.Println("resource:", nfe.Resource) // "item"
}

// errors.Join combines multiple errors into one (Go 1.20+).
err1 := errors.New("err1")
err2 := errors.New("err2")
combined := errors.Join(err1, err2)
</code></pre>
<h3>panic and recover</h3>
<p>Use <code>panic</code> for broken program invariants or truly unrecoverable situations; return <code>error</code> for expected failures. <code>recover</code> only works when called directly from a deferred function.</p>
<pre><code class="language-go">func mustPositive(n int) int {
	if n &lt;= 0 {
		panic(fmt.Sprintf("must be positive, got %d", n))
	}
	return n
}

func safeDiv(a, b int) (result int, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("recovered: %v", r)
		}
	}()
	return a / b, nil
}
</code></pre>
<hr />
<h2>Goroutines, channels, and synchronization</h2>
<pre><code class="language-plaintext">GMP model (Go runtime scheduler)

G = Goroutine (lightweight thread; initial stack ~2 KB, grows as needed)
M = OS thread
P = Processor (controlled by GOMAXPROCS)

  P1                P2
  ┌────────────┐   ┌────────────┐
  │ G1 running │   │ G3 running │
  │ ┌────────┐ │   │ ┌────────┐ │
  │ │ G2     │ │   │ │ G4     │ │ ← local run queue
  │ │ G5     │ │   └────────────┘
  └────────────┘
       M1               M2        ← OS threads
</code></pre>
<h3>Goroutines</h3>
<pre><code class="language-go">// go keyword: start a function concurrently.
go func() {
	fmt.Println("goroutine")
}()

// Wait for goroutines to finish.
var wg sync.WaitGroup
for i := 0; i &lt; 5; i++ {
	wg.Add(1)
	go func(n int) {
		defer wg.Done()
		fmt.Println(n)
	}(i) // Pass i as an argument to avoid closure capture issues.
}
wg.Wait()
</code></pre>
<h3>Channels</h3>
<pre><code class="language-go">ch := make(chan int)       // Unbuffered: send blocks until a receiver is ready.
bch := make(chan int, 10)  // Buffered: send blocks only when the buffer is full.

// Unbuffered: send and receive must be in separate goroutines.
go func() { ch &lt;- 42 }()
v := &lt;-ch

// Buffered: send and receive can be in the same goroutine within capacity.
bch &lt;- 1
bch &lt;- 2
fmt.Println(&lt;-bch, &lt;-bch) // 1 2

// Receiving from a closed, drained channel returns (zero, false).
v, ok := &lt;-ch // ok is false when the channel is closed and empty.
</code></pre>
<pre><code class="language-go">// range receives values until the channel is closed and drained.
ch2 := make(chan int, 3)
ch2 &lt;- 1; ch2 &lt;- 2; ch2 &lt;- 3
close(ch2) // The sender closes the channel.
for v := range ch2 {
	fmt.Println(v) // 1, 2, 3
}
</code></pre>
<h3>Channel direction</h3>
<pre><code class="language-go">// Directional types make intent explicit and catch mistakes at compile time.
func producer(ch chan&lt;- int) { // Send-only.
	for i := 0; i &lt; 5; i++ {
		ch &lt;- i
	}
	close(ch)
}

func consumer(ch &lt;-chan int) { // Receive-only.
	for v := range ch {
		fmt.Println(v)
	}
}

ch := make(chan int)
go producer(ch)
consumer(ch)
</code></pre>
<h3>select</h3>
<pre><code class="language-go">// select waits on multiple channel operations simultaneously.
// It picks one ready case at random when several are ready.
select {
case v := &lt;-ch1:
	fmt.Println("ch1:", v)
case v := &lt;-ch2:
	fmt.Println("ch2:", v)
case ch3 &lt;- data:
	fmt.Println("sent to ch3")
case &lt;-time.After(1 * time.Second):
	fmt.Println("timeout")
default:
	fmt.Println("no channel ready") // Non-blocking.
}
</code></pre>
<h3>sync and atomic</h3>
<pre><code class="language-go">// Mutex: protect shared state from concurrent access.
var mu sync.Mutex
var count int

mu.Lock()
count++
mu.Unlock()

// RWMutex: more efficient when reads are much more frequent than writes.
var rw sync.RWMutex
rw.RLock()  // Multiple goroutines can read simultaneously.
// ... read ...
rw.RUnlock()

// Once: run an initialization function exactly once.
var once sync.Once
once.Do(func() { /* called only the first time */ })

// atomic: low-overhead operations for simple counters and flags.
var n atomic.Int64
n.Add(1)
fmt.Println(n.Load())
</code></pre>
<blockquote>
<p><strong>Avoid goroutine leaks</strong> When a goroutine sends on a channel, always give it a way to stop if the receiver exits early.</p>
</blockquote>
<pre><code class="language-go">select {
case ch &lt;- result:
case &lt;-ctx.Done(): // Exit when the caller cancels.
	return
}
</code></pre>
<hr />
<h2>Context</h2>
<pre><code class="language-plaintext">Context tree

context.Background()
    └── WithCancel → ctx, cancel
            └── WithTimeout(ctx, 5s) → ctx2, cancel2
                    └── WithValue(ctx2, key, val) → ctx3
                                    ↓
                       Cancellation and deadlines propagate to child contexts.
</code></pre>
<p>Use <code>context.Context</code> to propagate deadlines, cancellation, and request-scoped metadata. Call the returned <code>cancel</code> function even when a timeout will eventually fire.</p>
<pre><code class="language-go">import "context"

// Timeout context.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel() // Always call cancel to release resources.

req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://example.com", nil)
if err != nil {
	return err
}

resp, err := http.DefaultClient.Do(req)
if err != nil {
	if errors.Is(err, context.DeadlineExceeded) {
		fmt.Println("timeout")
	}
	return err
}
defer resp.Body.Close()

// Cancellable context.
ctx2, cancel2 := context.WithCancel(context.Background())
go func() {
	&lt;-ctx2.Done() // Block until cancelled.
	fmt.Println("cancelled:", ctx2.Err())
}()
cancel2()

// context.WithValue carries request-scoped metadata.
// Use it only for small amounts of data; never as a substitute for function parameters.
type ctxKey string
const userKey ctxKey = "user"

ctx3 := context.WithValue(context.Background(), userKey, "alice")
user, ok := ctx3.Value(userKey).(string) // Type-assert with an ok check.
</code></pre>
<hr />
<h2>Generics</h2>
<p>Go 1.18 introduced type parameters for reusable, type-safe code.</p>
<h3>Type parameters</h3>
<pre><code class="language-go">// T and U can be any type.
func Map[T, U any](s []T, f func(T) U) []U {
	result := make([]U, len(s))
	for i, v := range s {
		result[i] = f(v)
	}
	return result
}

doubled := Map([]int{1, 2, 3}, func(n int) int { return n * 2 })
// [2 4 6]
</code></pre>
<h3>Type constraints</h3>
<pre><code class="language-go">import "cmp"

// cmp.Ordered allows &lt;, &gt;, ==  (int, float64, string, etc.).
func Min[T cmp.Ordered](a, b T) T {
	if a &lt; b {
		return a
	}
	return b
}

Min(3, 5)       // 3 (int)
Min(3.14, 2.71) // 2.71 (float64)
Min("b", "a")   // "a" (string)

// Custom constraint with ~ for underlying types.
type Number interface {
	~int | ~int64 | ~float64
}

func Sum[T Number](nums []T) T {
	var total T
	for _, n := range nums {
		total += n
	}
	return total
}
</code></pre>
<h3>Generic types</h3>
<pre><code class="language-go">type Stack[T any] struct {
	items []T
}

func (s *Stack[T]) Push(v T) {
	s.items = append(s.items, v)
}

func (s *Stack[T]) Pop() (T, bool) {
	if len(s.items) == 0 {
		var zero T
		return zero, false // Return the zero value of T.
	}
	v := s.items[len(s.items)-1]
	s.items = s.items[:len(s.items)-1]
	return v, true
}

s := Stack[string]{}
s.Push("Go")
s.Push("Generics")
v, _ := s.Pop() // "Generics"
</code></pre>
<h3>Generic methods (Go 1.27+)</h3>
<p>Starting with Go 1.27, a method can declare its own type parameters. This lets an operation associated with a type work with multiple argument types.</p>
<pre><code class="language-go">type Converter struct{}

func (Converter) Convert[T any](v T) T {
	return v
}

c := Converter{}
n := c.Convert(42)       // T = int
s := c.Convert("hello") // T = string
</code></pre>
<p>Interface methods cannot declare type parameters, and a generic method cannot implement an interface method.</p>
<h3>Generic function inference (Go 1.27+)</h3>
<p>Type arguments can now be inferred from the destination function type in assignments, conversions, composite literals, and channel sends.</p>
<pre><code class="language-go">func Stringify[T any](v T) string {
	return fmt.Sprint(v)
}

type IntFormatter func(int) string

var format IntFormatter = Stringify
formatters := []IntFormatter{Stringify}

ch := make(chan IntFormatter, 1)
ch &lt;- Stringify
</code></pre>
<hr />
<h2>Iterators</h2>
<p>Since Go 1.23, a function returning <code>iter.Seq</code> can be ranged over directly. When the caller breaks early, <code>yield</code> returns <code>false</code> so the producer can stop.</p>
<pre><code class="language-go">import "iter"

// Backward yields n-1 through 0.
func Backward(n int) iter.Seq[int] {
	return func(yield func(int) bool) {
		for i := n - 1; i &gt;= 0; i-- {
			if !yield(i) { // Caller broke out of the loop.
				return
			}
		}
	}
}

for i := range Backward(3) {
	fmt.Println(i) // 2, 1, 0
}

// maps.Keys returns an iter.Seq; slices.Collect converts it to a slice.
keys := slices.Collect(maps.Keys(m))
</code></pre>
<hr />
<h2>Testing</h2>
<pre><code class="language-go">// Place tests in xxx_test.go files.
package mypackage_test

import (
	"testing"

	"github.com/yourname/yourproject/mypackage"
)

func TestAdd(t *testing.T) {
	got := mypackage.Add(2, 3)
	if got != 5 {
		t.Errorf("Add(2, 3) = %d; want 5", got)
	}
}

// Table-driven tests are the idiomatic Go pattern.
func TestDivide(t *testing.T) {
	tests := []struct {
		name    string
		a, b    float64
		want    float64
		wantErr bool
	}{
		{"normal", 10, 2, 5, false},
		{"division by zero", 10, 0, 0, true},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := mypackage.Divide(tt.a, tt.b)
			if (err != nil) != tt.wantErr {
				t.Errorf("unexpected error: %v", err)
			}
			if got != tt.want {
				t.Errorf("got %v, want %v", got, tt.want)
			}
		})
	}
}

// Benchmark: run with go test -bench=.
func BenchmarkAdd(b *testing.B) {
	b.ReportAllocs() // Report memory allocations per operation.
	for i := 0; i &lt; b.N; i++ {
		mypackage.Add(2, 3)
	}
}
</code></pre>
<h3>Test helpers</h3>
<pre><code class="language-go">// t.Helper makes failures report the caller's line, not the helper's.
func requireNoError(t *testing.T, err error) {
	t.Helper()
	if err != nil {
		t.Fatal(err)
	}
}

func TestWriteFile(t *testing.T) {
	t.Setenv("APP_ENV", "test") // Restored automatically after the test.
	dir := t.TempDir()           // Deleted automatically after the test.
	t.Cleanup(func() {
		// Register arbitrary cleanup: reset mocks, close clients, etc.
	})

	path := filepath.Join(dir, "output.txt")
	requireNoError(t, os.WriteFile(path, []byte("hello"), 0o644))
}
</code></pre>
<pre><code class="language-bash">go test ./...          # Run all tests.
go test -race ./...    # Detect data races.
go test -cover ./...   # Show coverage.
</code></pre>
<hr />
<h2>Standard-library quick reference</h2>
<h3>fmt</h3>
<pre><code class="language-go">// Output.
fmt.Print("no newline")
fmt.Println("with newline")
fmt.Printf("formatted %s %d %v\n", "str", 42, true)
fmt.Fprintf(os.Stderr, "error: %v\n", err)

// Build strings.
s := fmt.Sprintf("Hello, %s!", name)
msg := fmt.Errorf("wrap: %w", err)

// Common format verbs.
// %v   default             %+v  struct with field names  %#v  Go syntax
// %T   type name           %d   decimal integer          %f   floating-point
// %s   string              %q   quoted string            %x   hexadecimal
// %p   pointer address     %b   binary                   %e   exponent
</code></pre>
<h3>strings</h3>
<pre><code class="language-go">import "strings"

strings.Contains("Hello", "ell")                    // true
strings.HasPrefix("Hello", "He")                    // true
strings.HasSuffix("Hello", "lo")                    // true
strings.Count("cheese", "e")                        // 3
strings.Index("Hello", "ll")                        // 2
strings.Replace("oink oink", "oink", "moo", 1)     // "moo oink"
strings.ReplaceAll("oink oink", "oink", "moo")      // "moo moo"
strings.ToUpper("hello")                            // "HELLO"
strings.ToLower("HELLO")                            // "hello"
strings.TrimSpace("  hello  ")                      // "hello"
strings.Trim("##hello##", "#")                      // "hello"
strings.Split("a,b,c", ",")                         // ["a" "b" "c"]
strings.Join([]string{"a", "b"}, "-")               // "a-b"
strings.Fields("a  b\tc")                           // ["a" "b" "c"]

// strings.Builder is efficient for repeated concatenation in a loop.
// A plain + is fine for a small number of concatenations.
var sb strings.Builder
for i := 0; i &lt; 5; i++ {
	fmt.Fprintf(&amp;sb, "%d", i)
}
sb.String() // "01234"
</code></pre>
<h3>strconv</h3>
<pre><code class="language-go">import "strconv"

strconv.Itoa(42)                       // "42"
strconv.Atoi("42")                     // 42, nil
strconv.ParseFloat("3.14", 64)         // 3.14, nil
strconv.FormatFloat(3.14, 'f', 2, 64)  // "3.14"
strconv.ParseBool("true")              // true, nil
strconv.FormatBool(true)               // "true"
</code></pre>
<h3>sort and slices</h3>
<pre><code class="language-go">import "sort"

nums := []int{5, 2, 4, 1, 3}
sort.Ints(nums)                              // [1 2 3 4 5]

words := []string{"b", "a", "c"}
sort.Strings(words)

// Custom sort.
sort.Slice(nums, func(i, j int) bool {
	return nums[i] &gt; nums[j] // Descending.
})
</code></pre>
<pre><code class="language-go">import (
	"cmp"
	"slices"
)

slices.Sort(nums)                                            // Ascending.
idx, found := slices.BinarySearch(nums, 3)                  // Requires sorted input.

// cmp.Compare avoids integer overflow in comparison functions.
slices.SortFunc(nums, func(a, b int) int { return cmp.Compare(b, a) }) // Descending.
</code></pre>
<h3>maps (Go 1.21+)</h3>
<pre><code class="language-go">import (
    "maps"
    "slices"
)

m := map[string]int{"a": 1, "b": 2}
m2 := maps.Clone(m)        // Shallow copy.
maps.Copy(m2, m)            // Copy all entries from m into m2.
delete(m, "a")              // delete is a built-in function.
keys := slices.Collect(maps.Keys(m)) // Collect keys into a slice.
</code></pre>
<h3>time</h3>
<pre><code class="language-go">import "time"

now := time.Now()
t := time.Date(2026, 6, 1, 12, 0, 0, 0, time.Local)

// Go uses a reference time (Mon Jan 2 15:04:05 MST 2006) as the layout.
now.Format("2006-01-02 15:04:05")
now.Format(time.RFC3339)                      // "2026-06-22T12:00:00+09:00"
parsed, _ := time.Parse("2006-01-02", "2026-06-22")

later := now.Add(24 * time.Hour)
diff := later.Sub(now)     // time.Duration
fmt.Println(diff.Hours())  // 24.0

time.Sleep(100 * time.Millisecond)
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
</code></pre>
<h3>os and filepath</h3>
<pre><code class="language-go">import (
	"os"
	"path/filepath"
)

// File I/O.
data, err := os.ReadFile("file.txt")
err = os.WriteFile("out.txt", data, 0644)

// Directory operations.
entries, _ := os.ReadDir(".")
for _, e := range entries {
	fmt.Println(e.Name(), e.IsDir())
}
os.MkdirAll("a/b/c", 0755)
os.Remove("file.txt")
os.RemoveAll("dir/")

// Environment variables.
home := os.Getenv("HOME")
os.Setenv("KEY", "value")

// Path manipulation.
filepath.Join("a", "b", "c")       // "a/b/c"
filepath.Base("/a/b/file.txt")      // "file.txt"
filepath.Dir("/a/b/file.txt")       // "/a/b"
filepath.Ext("file.txt")            // ".txt"
abs, _ := filepath.Abs("relative")  // Absolute path.
</code></pre>
<h3>encoding/json</h3>
<pre><code class="language-go">import "encoding/json"

type Point struct {
	X int `json:"x"`
	Y int `json:"y"`
}

// Encode.
data, err := json.Marshal(Point{X: 1, Y: 2})           // []byte
pretty, err := json.MarshalIndent(Point{X: 1}, "", "  ")

// Decode.
var p Point
err = json.Unmarshal(data, &amp;p)

// Streaming.
enc := json.NewEncoder(os.Stdout)
enc.Encode(p)

dec := json.NewDecoder(os.Stdin) // Accepts any io.Reader.
dec.Decode(&amp;p)

// When the type is unknown.
var v any
json.Unmarshal(data, &amp;v)
m := v.(map[string]any)
</code></pre>
<h4><code>encoding/json/v2</code> (Go 1.27+)</h4>
<p><code>encoding/json/v2</code> is a new JSON API whose behavior can be configured with options. It has stricter defaults than <code>encoding/json</code>, including rejecting invalid UTF-8 and duplicate names in JSON objects.</p>
<pre><code class="language-go">import jsonv2 "encoding/json/v2"

type Config struct {
	Port int `json:"port"`
}

data, err := jsonv2.Marshal(Config{Port: 8080})

var cfg Config
err = jsonv2.Unmarshal(
	data,
	&amp;cfg,
	jsonv2.RejectUnknownMembers(true),
)
</code></pre>
<p>The existing <code>encoding/json</code> package remains supported, so migration to v2 is not required. Its existing API behavior is preserved, although error message text may change because of the new underlying implementation.</p>
<h3><code>uuid</code> (Go 1.27+)</h3>
<pre><code class="language-go">import "uuid"

id := uuid.New()    // Use when no specific UUID version is required.
id7 := uuid.NewV7() // UUID v7 is convenient for chronological sorting.

parsed, err := uuid.Parse("f81d4fae-7dec-11d0-a765-00a0c91e6bf6")
if err != nil {
	log.Fatal(err)
}

fmt.Println(id, id7, parsed)
</code></pre>
<p><code>uuid.MustParse</code> panics on invalid input, so it is best suited to constants and tests.</p>
<h3>net/http</h3>
<pre><code class="language-go">import (
	"bytes"
	"context"
	"errors"
	"io"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

// Always set a timeout; the default client has none.
client := &amp;http.Client{Timeout: 10 * time.Second}

// GET request.
resp, err := client.Get("https://example.com")
if err != nil {
	return err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)

// Custom request with context.
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(jsonData))
if err != nil {
	return err
}
req.Header.Set("Content-Type", "application/json")
resp2, err := client.Do(req)
if err != nil {
	return err
}
defer resp2.Body.Close()

// HTTP server with timeouts (required in production).
mux := http.NewServeMux()
mux.HandleFunc("GET /hello/{name}", func(w http.ResponseWriter, r *http.Request) {
	name := r.PathValue("name") // Path parameters (Go 1.22+).
	fmt.Fprintf(w, "Hello, %s!", name)
})

server := &amp;http.Server{
	Addr:              ":8080",
	Handler:           mux,
	ReadHeaderTimeout: 5 * time.Second,
	ReadTimeout:       30 * time.Second,
	WriteTimeout:      30 * time.Second,
	IdleTimeout:       60 * time.Second,
}
go func() {
	if err := server.ListenAndServe(); err != nil &amp;&amp; !errors.Is(err, http.ErrServerClosed) {
		log.Printf("server error: %v", err)
	}
}()

// Graceful shutdown on SIGINT / SIGTERM.
shutdownCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
&lt;-shutdownCtx.Done()

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
	log.Printf("shutdown error: %v", err)
}
</code></pre>
<h3>log/slog (Go 1.21+)</h3>
<pre><code class="language-go">import "log/slog"

// Default logger writes text to stderr.
slog.Info("server started", "port", 8080)
slog.Error("request failed", "err", err)

// JSON handler for structured logging (e.g., cloud environments).
logger := slog.New(slog.NewJSONHandler(os.Stdout, &amp;slog.HandlerOptions{
	Level: slog.LevelDebug,
}))
logger.Info("user logged in", "userID", 42, "ip", "127.0.0.1")
// {"time":"...","level":"INFO","msg":"user logged in","userID":42,"ip":"127.0.0.1"}

// Add fields shared across multiple log calls.
logger.With("requestID", "abc123").Info("processing")
</code></pre>
<hr />
<h2>Tips and common mistakes</h2>
<h3>Goroutine leak</h3>
<pre><code class="language-go">// Bad: the goroutine blocks forever if no one receives from ch.
go func() {
	ch &lt;- result
}()

// Good: always provide a cancellation path.
go func() {
	select {
	case ch &lt;- result:
	case &lt;-ctx.Done():
		return
	}
}()
</code></pre>
<h3>nil interface trap</h3>
<pre><code class="language-go">// Bad: even when *MyError is nil, the interface value is non-nil.
func getError() error {
	var err *MyError = nil
	return err // The returned error interface is non-nil!
}

if getError() != nil { // true — this branch is taken unexpectedly.
	fmt.Println("this prints unexpectedly")
}

// Good: return nil directly.
func getError() error {
	return nil
}
</code></pre>
<h3>Pre-allocate slice capacity</h3>
<pre><code class="language-go">// Bad: append may reallocate the backing array many times.
result := []int{}
for i := 0; i &lt; 10000; i++ {
	result = append(result, i)
}

// Good: allocate the full capacity upfront.
result := make([]int, 0, 10000)
for i := 0; i &lt; 10000; i++ {
	result = append(result, i)
}
</code></pre>
<h3>for-loop variable capture (fixed in Go 1.22)</h3>
<pre><code class="language-go">// Go 1.21 and earlier: all goroutines share the same i variable.
for i := 0; i &lt; 5; i++ {
	go func() { fmt.Println(i) }() // May print 5 five times.
}

// Go 1.22+: each iteration creates a new i variable.
// The above code now correctly prints 0, 1, 2, 3, 4 in some order.

// Workaround for Go 1.21 and earlier.
for i := 0; i &lt; 5; i++ {
	i := i // Shadow i with a new variable for this iteration.
	go func() { fmt.Println(i) }()
}
</code></pre>
<hr />
<h2>Modules and packages</h2>
<pre><code class="language-bash"># Initialize a module.
go mod init github.com/yourname/yourproject

# Go 1.27
go get go@1.27

go get github.com/some/package@v1.2.3   # Add a dependency.
go mod tidy                              # Remove unused dependencies.
go mod vendor                            # Vendor dependencies.
go build ./...                           # Build.
go test ./...                            # Test.
go test -race ./...                      # Detect data races.
go vet ./...                             # Static analysis.
go fmt ./...                             # Format.
</code></pre>
<hr />
<h2>Further reading</h2>
<ul>
<li><a href="https://pkg.go.dev">Go package documentation</a></li>
<li><a href="https://go.dev/ref/spec">The Go language specification</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Go チートシート]]></title><description><![CDATA[Go 1.27の実用チートシート。基本構文、スライス・マップ、インターフェース、エラー処理、goroutine・channel、context、ジェネリクス、テストをコード例でまとめています。]]></description><link>https://nobuo-miura.hashnode.dev/go</link><guid isPermaLink="true">https://nobuo-miura.hashnode.dev/go</guid><category><![CDATA[Go Language]]></category><category><![CDATA[golang]]></category><category><![CDATA[cheatsheet]]></category><dc:creator><![CDATA[Nobuo Miura]]></dc:creator><pubDate>Fri, 27 Nov 2026 10:30:03 GMT</pubDate><content:encoded><![CDATA[<p>Go 1.27 をベースにしたチートシートです。</p>
<hr />
<h2>基本構造</h2>
<pre><code class="language-go">package main  // 実行可能バイナリは必ず package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Println("Hello, Go 1.27")
    os.Exit(0)
}
</code></pre>
<ul>
<li>ファイルの先頭に必ず <code>package</code> 宣言</li>
<li><code>import</code> はグループ化推奨（標準ライブラリ → 外部パッケージの順）</li>
<li><code>main()</code> がエントリポイント</li>
</ul>
<hr />
<h2>変数・定数・型</h2>
<h3>変数宣言</h3>
<pre><code class="language-go">// var
var name = "Gopher" // string(初期値から型を推論)
var age int          // 初期値なしでは型の指定が必要。ゼロ値 = 0
var id int64 = 42    // 推論される int ではなく int64 にしたい場合は明示

// 短縮宣言（関数内のみ）
city := "Tokyo"

// 複数同時宣言
var (
    x, y int = 1, 2
    msg  string
)
</code></pre>
<p>初期値があれば <code>var name = "Gopher"</code> のように型推論が利用できます。<br />初期値がない場合は <code>var age int</code> のように型指定が必要です。<br /><code>:=</code> は関数内でのみ使え、左辺に少なくとも1つの新しい変数が必要です。</p>
<h3>型とゼロ値</h3>
<p><a href="https://go.dev/ref/spec#The_zero_value">公式リファレンス - ゼロ値</a></p>
<table>
<thead>
<tr>
<th>型の分類</th>
<th>型</th>
<th>ゼロ値</th>
</tr>
</thead>
<tbody><tr>
<td>数値</td>
<td>整数・浮動小数点・複素数</td>
<td><code>0</code>（複素数は <code>0 + 0i</code>）</td>
</tr>
<tr>
<td>文字列</td>
<td><code>string</code></td>
<td><code>""</code></td>
</tr>
<tr>
<td>真偽値</td>
<td><code>bool</code></td>
<td><code>false</code></td>
</tr>
<tr>
<td>配列</td>
<td><code>[N]T</code></td>
<td>すべての要素が <code>T</code> のゼロ値</td>
</tr>
<tr>
<td>構造体</td>
<td><code>struct</code></td>
<td>すべてのフィールドが各型のゼロ値</td>
</tr>
<tr>
<td>参照を含む型</td>
<td>pointer, slice, map, chan, func, interface</td>
<td><code>nil</code></td>
</tr>
<tr>
<td>定義型</td>
<td><code>type UserID int</code> など</td>
<td>基底型のゼロ値</td>
</tr>
</tbody></table>
<h3>基本型</h3>
<p><a href="https://go.dev/ref/spec#Types">公式リファレンス - 型一覧</a></p>
<table>
<thead>
<tr>
<th>分類</th>
<th>型</th>
<th>補足</th>
</tr>
</thead>
<tbody><tr>
<td>真偽値</td>
<td><code>bool</code></td>
<td><code>true</code> または <code>false</code></td>
</tr>
<tr>
<td>文字列</td>
<td><code>string</code></td>
<td>不変なバイト列</td>
</tr>
<tr>
<td>符号付き整数</td>
<td><code>int</code>, <code>int8</code>, <code>int16</code>, <code>int32</code>, <code>int64</code></td>
<td><code>int</code> のビット幅は実装依存</td>
</tr>
<tr>
<td>符号なし整数</td>
<td><code>uint</code>, <code>uint8</code>, <code>uint16</code>, <code>uint32</code>, <code>uint64</code>, <code>uintptr</code></td>
<td><code>uintptr</code> はポインタのビット列を保持できる整数型</td>
</tr>
<tr>
<td>エイリアス</td>
<td><code>byte</code>, <code>rune</code></td>
<td>それぞれ <code>uint8</code>, <code>int32</code> のエイリアス</td>
</tr>
<tr>
<td>浮動小数点</td>
<td><code>float32</code>, <code>float64</code></td>
<td>IEEE 754</td>
</tr>
<tr>
<td>複素数</td>
<td><code>complex64</code>, <code>complex128</code></td>
<td>実部・虚部がそれぞれ <code>float32</code> / <code>float64</code></td>
</tr>
</tbody></table>
<pre><code class="language-go">// 整数
var i8  int8  = 127          // -128 〜 127
var i64 int64 = 9223372036854775807
var u   uint  = 42           // 符号なし
var ptr uintptr              // ポインタ幅

// 浮動小数点
var f32 float32 = 3.14
var f64 float64 = 3.141592653589793

// 複素数
var c complex128 = 1 + 2i

// 文字列（不変なバイト列。通常は UTF-8 テキストとして扱うが、不正 UTF-8 も保持可能）
s := "日本語OK"
r := []rune(s) // Unicode コードポイントで扱う
b := []byte(s) // バイト列で扱う

// rune = int32 のエイリアス（Unicode コードポイント）
var ch rune = '🐹'
</code></pre>
<h3>型変換</h3>
<pre><code class="language-go">i := 42
f := float64(i)    // 必ず明示して変換する
s := fmt.Sprintf("%d", i) // 数値→文字列
n, _ := strconv.Atoi("123") // 文字列→数値
</code></pre>
<h3>定数</h3>
<pre><code class="language-go">const Pi = 3.14159

// iota：連番定数
type Weekday int
const (
    Sunday Weekday = iota // 0
    Monday                // 1
    Tuesday               // 2
)

// ビットフラグパターン
type Permission uint
const (
    Read    Permission = 1 &lt;&lt; iota // 1
    Write                          // 2
    Execute                        // 4
)
</code></pre>
<h3>ポインタ</h3>
<pre><code class="language-go">x := 10
p := &amp;x      // アドレス取得
*p = 20      // デリファレンス
fmt.Println(x) // 20

// new でゼロ値ポインタ生成
p2 := new(int) // *int、値は 0

// Go 1.26 から：式で初期値を指定できる（Go 1.25 以前では不可）
p3 := new(42) // *int、値は 42
</code></pre>
<hr />
<h2>制御構文</h2>
<h3>if</h3>
<pre><code class="language-go">// 初期化ステートメント付き
if err := doSomething(); err != nil {
    fmt.Println("error:", err)
}

// 通常 if-else
if 0 &lt; x {
    fmt.Println("positive")
} else if x &lt; 0 {
    fmt.Println("negative")
} else {
    fmt.Println("zero")
}
</code></pre>
<h3>for （Go に while はない）</h3>
<pre><code class="language-go">// C スタイル
for i := 0; i &lt; 5; i++ { }

// while 相当
for 0 &lt; n { n-- }

// 無限ループ
for {
    if done { break }
}

// range：インデックス＋値
for i, v := range []int{10, 20, 30} {
    fmt.Println(i, v) // 0 10 / 1 20 / 2 30
}

// インデックスだけ
for i := range slice { }

// 値だけ（_ で捨てる）
for _, v := range slice { }

// マップ
for k, v := range m { }

// 文字列は rune でイテレート
for i, r := range "日本語" {
    fmt.Printf("%d: %c\n", i, r)
}
// 0: 日
// 3: 本
// 6: 語
</code></pre>
<h3>switch</h3>
<pre><code class="language-go">// 式 switch（fallthrough は明示が必要）
switch os := runtime.GOOS; os {
case "darwin":
    fmt.Println("macOS")
case "linux":
    fmt.Println("Linux")
default:
    fmt.Println("Other")
}

// 条件なし switch（if-else チェーンの代替）
switch {
case 100 &lt; x:
    fmt.Println("big")
case 10 &lt; x:
    fmt.Println("medium")
default:
    fmt.Println("small")
}

// type switch（インターフェース判別）
func describe(i any) {
    switch v := i.(type) {
    case int:
        fmt.Printf("int: %d\n", v)
    case string:
        fmt.Printf("string: %q\n", v)
    default:
        fmt.Printf("unknown: %T\n", v)
    }
}
</code></pre>
<h3>defer</h3>
<p>defer は「その関数が終了する直前に実行する処理を予約する」ための仕組みです。<br />主にファイルやレスポンスボディ、ロックの解放等に使用します。</p>
<pre><code class="language-go">func writeFile(path string) error {
    f, err := os.Create(path)
    if err != nil { return err }
    defer f.Close() // 関数終了時に必ず実行

    // defer は LIFO 順
    defer fmt.Println("3rd")
    defer fmt.Println("2nd")
    defer fmt.Println("1st")
    // → "1st", "2nd", "3rd" の順に出力

    return nil
}
</code></pre>
<p>:::message <code>defer</code> は引数をその時点で評価します。 ループ内で使う場合、<code>defer</code> は<strong>関数が終わるまで実行されない</strong>点に注意が必要です。 ループごとにファイルを開く処理などは、<code>defer</code> に頼らず即クローズするか、処理を別関数に切り出してください。 :::</p>
<hr />
<h2>関数</h2>
<h3>基本</h3>
<pre><code class="language-go">// 複数戻り値
func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("division by zero")
    }
    return a / b, nil
}

result, err := divide(10, 3)

// 名前付き戻り値（ドキュメント目的・短い関数向け）
func minMax(nums []int) (min, max int) {
    min, max = nums[0], nums[0]
    for _, n := range nums[1:] {
        if n &lt; min { min = n }
        if n &gt; max { max = n }
    }
    return // naked return
}
</code></pre>
<h3>可変長引数</h3>
<pre><code class="language-go">func sum(nums ...int) int {
    total := 0
    for _, n := range nums {
        total += n
    }
    return total
}

sum(1, 2, 3)
nums := []int{1, 2, 3}
sum(nums...) // スライスを展開
</code></pre>
<h3>第一級関数・クロージャ</h3>
<p>Go では関数を値として扱えます。変数への代入、引数としての受け渡し、戻り値としての返却ができる性質を<strong>第一級関数</strong>と呼びます。</p>
<p><strong>クロージャ</strong>は、関数が定義された外側の変数を参照・保持できる関数値です。外側の関数が終了した後も、キャプチャした変数の状態を保持できます。</p>
<pre><code class="language-go">// 関数を変数に代入
add := func(a, b int) int { return a + b }

// 関数を引数に渡す
apply := func(f func(int, int) int, x, y int) int {
    return f(x, y)
}
apply(add, 3, 4) // 7

// クロージャ：外側の変数をキャプチャ
func counter() func() int {
    n := 0
    return func() int {
        n++
        return n
    }
}
c := counter()
c() // 1
c() // 2
</code></pre>
<h3>init 関数</h3>
<p><code>init</code> はパッケージの初期化時に自動で呼ばれる特別な関数です。<br /><code>main</code> 関数より前に実行され、1つのパッケージ内に複数定義できます。</p>
<p>通常のアプリケーション初期化は <code>main</code> や明示的な初期化関数で行う方が、依存関係とエラー処理を追いやすくなります。<br /><code>init</code> はパッケージ内部の登録処理など、実行順序を意識せずに済む用途に限定するのが無難です。</p>
<pre><code class="language-go">// パッケージ初期化時に自動実行（複数定義可）
func init() {
    // ドライバやハンドラの登録など
}
</code></pre>
<hr />
<h2>配列・スライス・マップ</h2>
<h3>メモリレイアウト概念図</h3>
<pre><code class="language-plaintext">配列（固定長・値型）
┌───┬───┬───┬───┬───┐
│ 0 │ 1 │ 2 │ 3 │ 4 │  ← 連続したメモリ領域（配置はコンパイラが決定）
└───┴───┴───┴───┴───┘

スライス（可変長ビュー）
┌────────┬──────┬──────┐
│ ptr    │ len  │ cap  │  ← スライスヘッダ（3ワード）
└────┬───┴──────┴──────┘
     ↓
┌───┬───┬───┬───┬───┬───┐
│ 0 │ 1 │ 2 │ 3 │   │   │  ← 別の場所に確保された配列
└───┴───┴───┴───┴───┴───┘
     ↑           ↑
    len=4       cap=6

※ 配列・スライスの実際の配置（スタック/ヒープ）はエスケープ解析で決まります
</code></pre>
<h3>配列</h3>
<p>配列は長さが型の一部である「固定長」のコレクションです。<code>[3]int</code> と <code>[4]int</code> は別の型になり、代入や関数引数への受け渡しでは要素ごとコピーされます。要素数が固定の値を扱う場合に使います。</p>
<pre><code class="language-go">var a [3]int              // [0 0 0]
b := [3]int{1, 2, 3}
c := [...]int{4, 5, 6}    // 長さ自動推論

// 配列は値型（コピーされる）
d := b
d[0] = 99 // b は変わらない
</code></pre>
<h3>スライス</h3>
<p>スライスは配列の一部または全体を参照する、可変長のビューです。</p>
<p>配列との主な違いは、長さが型の一部ではないこと、代入しても要素全体はコピーされず基底配列を共有し得ること、<code>append</code> で長さを増やせます。</p>
<pre><code class="language-go">// 生成
s := []int{1, 2, 3}
s2 := make([]int, 5)      // len=5, cap=5
s3 := make([]int, 3, 10)  // len=3, cap=10

// 操作
s = append(s, 4, 5)       // cap 超えると新配列にコピー
s = append(s, []int{6, 7}...)

// スライシング（同じ配列を参照）
sub := s[1:3]             // s[1], s[2]（元配列の参照）
sub2 := s[1:3:3]          // 第3引数でキャップを制限

// コピー（独立したメモリ）
dst := make([]int, len(s))
copy(dst, s)

// 削除（順序維持）
i := 2
s = append(s[:i], s[i+1:]...)

// 長さ・容量
fmt.Println(len(s), cap(s))
</code></pre>
<p>:::message alert <code>sub := s[1:3]</code> のようにスライシングすると、<code>sub</code> と <code>s</code> は同じ配列を指します。 <code>sub</code> を変更すると <code>s</code> にも影響します。独立させるには <code>copy</code> を使いましょう。 :::</p>
<h3>マップ</h3>
<p>マップはキーと値を対応付けて保持するコレクションです。 要素の順序は保証されず、キーには比較可能な型（数値、文字列、ポインタ、配列、比較可能な構造体など）を使えます。 slice、map、func はキーには使えません。</p>
<pre><code class="language-go">// 生成
m := map[string]int{"a": 1, "b": 2}
m2 := make(map[string]int)

// 操作
m["c"] = 3
delete(m, "a")

// 存在確認
v, ok := m["x"]  // ok=false なら存在しない
if ok {
    fmt.Println(v)
}

// イテレート（順序は不定）
for k, v := range m {
    fmt.Println(k, v)
}
</code></pre>
<p>:::message マップのゼロ値は <code>nil</code>です。 <code>nil</code> マップへの書き込みはパニックになりますので、必ず <code>make</code> か初期化してから使います。 :::</p>
<hr />
<h2>構造体とメソッド</h2>
<h3>構造体</h3>
<p>構造体は、関連する複数の値をフィールドとしてひとまとまりにした独自の型です。 フィールド名が大文字で始まると他パッケージから参照でき、小文字で始まるとパッケージ内だけで使えます。</p>
<pre><code class="language-go">type Person struct {
    Name string // 先頭が大文字 = 公開フィールド
    Age  int
    addr string // 先頭が小文字 = 非公開フィールド
}

// 初期化
p1 := Person{Name: "Alice", Age: 30} // 推奨
p2 := Person{"Bob", 25, "Tokyo"} // フィールド順（非推奨）
p3 := new(Person)                // *Person、ゼロ値

// 埋め込み（継承ではなくコンポジション）
type Employee struct {
    Person             // フィールドとメソッドを昇格
    Department string
}

e := Employee{Person: Person{Name: "Carol", Age: 28}, Department: "Eng"}
fmt.Println(e.Name) // Person.Name に透過アクセス

// Go 1.27から：昇格したフィールドをキーに直接指定できる
e2 := Employee{Name: "Eve", Age: 32, Department: "Sales"}
</code></pre>
<p>Go 1.27 から、構造体リテラルのキーには、その構造体で有効なフィールドセレクタを指定できます。上の <code>Name</code> と <code>Age</code> は、埋め込まれた <code>Person</code> から昇格したフィールドです。</p>
<h3>メソッド</h3>
<p>メソッドは特定の型に関連付ける関数です。 関数名の前にレシーバを指定し、値レシーバなら値のコピーを、ポインタレシーバなら元の値へのポインタを受け取ります。</p>
<pre><code class="language-go">// 値レシーバ（コピーを受け取る）
func (p Person) Greet() string {
    return "Hi, I'm " + p.Name
}

// ポインタレシーバ（元の値を変更できる）
func (p *Person) Birthday() {
    p.Age++
}

p := Person{Name: "Dave", Age: 20}
p.Birthday()     // Go が自動的に &amp;p を渡す
fmt.Println(p.Age) // 21
</code></pre>
<p>:::message <strong>ポインタレシーバを選ぶ基準</strong></p>
<ul>
<li>構造体を変更する必要がある場合 → ポインタレシーバ</li>
<li>構造体が大きい場合（コピーコスト）→ ポインタレシーバ</li>
<li>それ以外 → 値レシーバでも可</li>
</ul>
<p>一つのメソッドでポインタレシーバを使ったら、同じ型の他メソッドも統一するのがベストプラクティスです。 :::</p>
<h3>タグ</h3>
<p>構造体タグはフィールドに付けられるメタデータです。 タグ自体に言語機能はなく、<code>encoding/json</code> や ORM などがリフレクションを通じて解釈します。 慣例として、空白区切りで <code>json:"id"</code> のような <code>キー:"値"</code> を記述します。</p>
<pre><code class="language-go">type User struct {
    ID    int    `json:"id" db:"user_id"`
    Email string `json:"email,omitempty"`
}

// encoding/json が reflect でタグを参照
data, _ := json.Marshal(User{ID: 1, Email: ""})
// → {"id":1}  (omitempty で Email は省略)
</code></pre>
<hr />
<h2>インターフェース</h2>
<h3>インターフェースの仕組み</h3>
<p>インターフェースは「その型が持つべきメソッドの集合」を定義する型です。 必要なメソッドをすべて実装した型は、宣言なしでそのインターフェースを実装します。 具体的な型ではなく振る舞いに依存した設計に使います。</p>
<pre><code class="language-go">type Shape interface {
    Area() float64
    Perimeter() float64
}

type Circle struct{ Radius float64 }

func (c Circle) Area() float64      { return math.Pi * c.Radius * c.Radius }
func (c Circle) Perimeter() float64 { return 2 * math.Pi * c.Radius }

// 実装は暗黙的（implements キーワード不要）
var s Shape = Circle{Radius: 5}
fmt.Println(s.Area())
</code></pre>
<h3>型アサーション・型スイッチ</h3>
<pre><code class="language-go">// 型アサーション
c, ok := s.(Circle)
if ok {
    fmt.Println("radius:", c.Radius)
}

// ok なしは失敗時にパニック
c2 := s.(Circle)

// 型スイッチ（前述の switch セクション参照）
</code></pre>
<h3>空インターフェース・any</h3>
<pre><code class="language-go">// any は interface{} のエイリアス（Go 1.18〜）
func printAny(v any) {
    fmt.Printf("%T: %v\n", v, v)
}

printAny(42)
printAny("hello")
printAny([]int{1, 2, 3})
</code></pre>
<h3>よく使う小さなインターフェース</h3>
<pre><code class="language-go">// io.Reader / io.Writer
type Reader interface { Read(p []byte) (n int, err error) }
type Writer interface { Write(p []byte) (n int, err error) }

// fmt.Stringer：String() を実装すると fmt.Println で出力可能
type Stringer interface { String() string }

func (p Person) String() string {
    return fmt.Sprintf("%s (%d)", p.Name, p.Age)
}

fmt.Println(Person{Name: "Eve", Age: 22}) // Eve (22)
</code></pre>
<hr />
<h2>エラーハンドリング</h2>
<h3>基本パターン</h3>
<pre><code class="language-go">// error は組み込みインターフェース
// type error interface { Error() string }

f, err := os.Open("file.txt")
if err != nil {
    return fmt.Errorf("open file: %w", err) // %w でラップ
}
defer f.Close()
</code></pre>
<h3>カスタムエラー</h3>
<pre><code class="language-go">type NotFoundError struct {
    Resource string
    ID       int
}

func (e *NotFoundError) Error() string {
    return fmt.Sprintf("%s (id=%d) not found", e.Resource, e.ID)
}

func findUser(id int) (*User, error) {
    if id &lt;= 0 {
        return nil, &amp;NotFoundError{Resource: "user", ID: id}
    }
    // ...
}
</code></pre>
<h3>errors パッケージ</h3>
<pre><code class="language-go">import "errors"

// errors.Is：sentinel エラーを %w でラップして伝播させ、チェーンを辿って比較
var ErrNotFound = errors.New("not found")

func fetchUser(id int) (*User, error) {
    if id &lt;= 0 {
        return nil, fmt.Errorf("fetchUser: %w", ErrNotFound) // %w でラップ
    }
    // ...
    return nil, nil
}

_, err := fetchUser(-1) // fetchUser は (*User, error) を返すので _ で捨てる
if errors.Is(err, ErrNotFound) {
    fmt.Println("not found")
}

// errors.As：カスタムエラー型をチェーンから取り出して型変換
func findItem(id int) error {
    return fmt.Errorf("findItem: %w", &amp;NotFoundError{Resource: "item", ID: id})
}

var nfe *NotFoundError
if errors.As(findItem(42), &amp;nfe) {
    fmt.Println("resource:", nfe.Resource) // "item"
}

// Go 1.26〜：errors.As の型安全なジェネリクス版
if nfe, ok := errors.AsType[*NotFoundError](findItem(42)); ok {
    fmt.Println("resource:", nfe.Resource) // "item"
}

// errors.Join（Go 1.20〜）：複数エラーを結合
err1 := errors.New("err1")
err2 := errors.New("err2")
combined := errors.Join(err1, err2)
</code></pre>
<h3>panic と recover</h3>
<pre><code class="language-go">// panic：回復不能なエラーに使う（通常は error を返す）
func mustPositive(n int) int {
    if n &lt;= 0 {
        panic(fmt.Sprintf("must be positive, got %d", n))
    }
    return n
}

// recover：defer 内でのみ有効
func safeDiv(a, b int) (result int, err error) {
    defer func() {
        if r := recover(); r != nil {
            err = fmt.Errorf("recovered: %v", r)
        }
    }()
    return a / b, nil
}
</code></pre>
<hr />
<h2>goroutine・channel</h2>
<h3>並行処理モデル概念図</h3>
<pre><code class="language-plaintext">goroutine の実行モデル（GMP モデル）

G = Goroutine（軽量スレッド、初期スタック 2KB・必要に応じて拡張）
M = OS Thread
P = Processor（GOMAXPROCS で制御）

  P1                P2
  ┌────────────┐   ┌────────────┐
  │ G1 running │   │ G3 running │
  │ ┌────────┐ │   │ ┌────────┐ │
  │ │ G2     │ │   │ │ G4     │ │ ← ローカルキュー
  │ │ G5     │ │   │ └────────┘ │
  │ └────────┘ │   └──────┬─────┘
  └──────┬─────┘          │
         │                │
         M1               M2       ← OS スレッド
</code></pre>
<h3>goroutine</h3>
<pre><code class="language-go">// go キーワードで非同期実行
go func() {
    fmt.Println("goroutine")
}()

// 完了を待つ
var wg sync.WaitGroup
for i := 0; i &lt; 5; i++ {
    wg.Add(1)
    go func(n int) {
        defer wg.Done()
        fmt.Println(n)
    }(i) // i を引数で渡す（クロージャキャプチャを避ける）
}
wg.Wait()
</code></pre>
<h3>channel</h3>
<pre><code class="language-go">// 生成
ch := make(chan int)       // 非バッファチャネル
bch := make(chan int, 10)  // バッファチャネル（容量10）

// 送受信（非バッファは送受信を別ゴルーチンで行う）
go func() { ch &lt;- 42 }() // 別ゴルーチンで送信
v := &lt;-ch                 // メインゴルーチンで受信

// バッファチャネルは容量内なら同一ゴルーチンでも送受信可
bch &lt;- 1
bch &lt;- 2
fmt.Println(&lt;-bch, &lt;-bch)

// クローズ
close(ch)
v, ok := &lt;-ch // ok=false ならクローズ済み・ゼロ値が返る

// range で受信（クローズまで）
for v := range ch {
    fmt.Println(v)
}
</code></pre>
<h3>チャネルの方向性</h3>
<pre><code class="language-go">// 送信専用・受信専用チャネルで意図を明確化
func producer(ch chan&lt;- int) { // 送信専用
    for i := 0; i &lt; 5; i++ {
        ch &lt;- i
    }
    close(ch)
}

func consumer(ch &lt;-chan int) { // 受信専用
    for v := range ch {
        fmt.Println(v)
    }
}

ch := make(chan int)
go producer(ch)
consumer(ch)
</code></pre>
<h3>select</h3>
<pre><code class="language-go">// 複数チャネルを同時に待機
select {
case v := &lt;-ch1:
    fmt.Println("ch1:", v)
case v := &lt;-ch2:
    fmt.Println("ch2:", v)
case ch3 &lt;- data:
    fmt.Println("sent to ch3")
case &lt;-time.After(1 * time.Second):
    fmt.Println("timeout")
default:
    fmt.Println("no channel ready") // ノンブロッキング
}
</code></pre>
<h3>sync パッケージ</h3>
<pre><code class="language-go">// Mutex：共有リソース保護
var mu sync.Mutex
var count int

mu.Lock()
count++
mu.Unlock()

// RWMutex：読み取り多・書き込み少の場合に有効
var rw sync.RWMutex
rw.RLock()  // 複数ゴルーチンが同時に読める
// ...
rw.RUnlock()

// Once：初期化を一度だけ実行
var once sync.Once
once.Do(func() { /* 初期化処理 */ })

// atomic：シンプルなカウンタに
var n atomic.Int64
n.Add(1)
fmt.Println(n.Load())
</code></pre>
<hr />
<h2>コンテキスト</h2>
<pre><code class="language-plaintext">コンテキストツリー

context.Background()
    └── WithCancel → ctx, cancel
            └── WithTimeout(ctx, 5s) → ctx2, cancel2
                    └── WithValue(ctx2, key, val) → ctx3
                                ↓
                       キャンセル・タイムアウトは
                       子コンテキストに伝播する
</code></pre>
<pre><code class="language-go">import "context"

// タイムアウト付きコンテキスト
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel() // リソースリークを防ぐため必ず呼ぶ

// HTTP リクエスト例
req, err := http.NewRequestWithContext(ctx, "GET", "https://example.com", nil)
if err != nil {
    return err
}

resp, err := http.DefaultClient.Do(req)
if err != nil {
    if errors.Is(err, context.DeadlineExceeded) {
        fmt.Println("timeout")
    }
    return err
}
defer resp.Body.Close()

// キャンセル可能コンテキスト
ctx2, cancel2 := context.WithCancel(context.Background())
go func() {
    &lt;-ctx2.Done() // キャンセルを検知
    fmt.Println("cancelled:", ctx2.Err())
}()
cancel2()

// 値の伝達（リクエストスコープの少量メタデータに限定する）
// ビジネスロジックの引数渡しには使わない
type ctxKey string
const userKey ctxKey = "user"

ctx3 := context.WithValue(context.Background(), userKey, "alice")
user, ok := ctx3.Value(userKey).(string) // 型アサーションは ok チェック付き
</code></pre>
<hr />
<h2>ジェネリクス</h2>
<p>Go 1.18 で導入。型パラメータで再利用可能なコードを書けます。</p>
<h3>型パラメータの基本</h3>
<pre><code class="language-go">// T はなんでも受け取れる（any = interface{}）
func Map[T, U any](s []T, f func(T) U) []U {
    result := make([]U, len(s))
    for i, v := range s {
        result[i] = f(v)
    }
    return result
}

doubled := Map([]int{1, 2, 3}, func(n int) int { return n * 2 })
// [2 4 6]
</code></pre>
<h3>型制約（Constraint）</h3>
<pre><code class="language-go">import "cmp"

// cmp.Ordered：&lt;, &gt;, == が使える型（int, float64, string など）
func Min[T cmp.Ordered](a, b T) T {
    if a &lt; b { return a }
    return b
}

Min(3, 5)       // 3 (int)
Min(3.14, 2.71) // 2.71 (float64)
Min("b", "a")   // "a" (string)

// カスタム制約
type Number interface {
    ~int | ~int64 | ~float64
}

func Sum[T Number](nums []T) T {
    var total T
    for _, n := range nums {
        total += n
    }
    return total
}
</code></pre>
<h3>ジェネリック構造体</h3>
<pre><code class="language-go">type Stack[T any] struct {
    items []T
}

func (s *Stack[T]) Push(v T) {
    s.items = append(s.items, v)
}

func (s *Stack[T]) Pop() (T, bool) {
    if len(s.items) == 0 {
        var zero T
        return zero, false
    }
    v := s.items[len(s.items)-1]
    s.items = s.items[:len(s.items)-1]
    return v, true
}

s := Stack[string]{}
s.Push("Go")
s.Push("Generics")
v, _ := s.Pop() // "Generics"
</code></pre>
<h3>ジェネリックメソッド（Go 1.27〜）</h3>
<p>Go 1.27 から、メソッド自身が型パラメータを宣言できます。型に属する操作として、複数の型に対応するメソッドを定義できます。</p>
<pre><code class="language-go">type Converter struct{}

func (Converter) Convert[T any](v T) T {
    return v
}

c := Converter{}
n := c.Convert(42)      // T = int
s := c.Convert("hello") // T = string
</code></pre>
<p>インターフェースのメソッドは型パラメータを宣言できず、ジェネリックメソッドでインターフェースメソッドを実装することもできません。</p>
<h3>ジェネリック関数の型推論（Go 1.27〜）</h3>
<p>ジェネリック関数を関数型へ代入・変換する場合や、複合リテラル、チャネル送信で使う場合も、代入先の型から型引数を推論できます。</p>
<pre><code class="language-go">func Stringify[T any](v T) string {
    return fmt.Sprint(v)
}

type IntFormatter func(int) string

var format IntFormatter = Stringify
formatters := []IntFormatter{Stringify}

ch := make(chan IntFormatter, 1)
ch &lt;- Stringify
</code></pre>
<hr />
<h2>イテレータ</h2>
<p>Go 1.23 以降では、<code>iter.Seq</code> を返す関数を <code>range</code> で直接イテレートできます。 呼び出し側が途中で <code>break</code> した場合は、<code>yield</code> が <code>false</code> を返すため生成側も停止できます。</p>
<pre><code class="language-go">import "iter"

// n-1 から 0 までを返すイテレータ
func Backward(n int) iter.Seq[int] {
    return func(yield func(int) bool) {
        for i := n - 1; i &gt;= 0; i-- {
            if !yield(i) { // 呼び出し側が break した
                return
            }
        }
    }
}

for i := range Backward(3) {
    fmt.Println(i) // 2, 1, 0
}

// maps.Keys などの iter.Seq は slices.Collect でスライス化できる
keys := slices.Collect(maps.Keys(m))
</code></pre>
<hr />
<h2>テスト</h2>
<pre><code class="language-go">// xxx_test.go ファイルに書く
package mypackage_test

import (
    "os"
    "path/filepath"
    "testing"

    "github.com/yourname/yourproject/mypackage"
)

func TestAdd(t *testing.T) {
    got := mypackage.Add(2, 3)
    if got != 5 {
        t.Errorf("Add(2,3) = %d; want 5", got)
    }
}

// テーブル駆動テスト（推奨パターン）
func TestDivide(t *testing.T) {
    tests := []struct {
        name    string
        a, b    float64
        want    float64
        wantErr bool
    }{
        {"normal", 10, 2, 5, false},
        {"division by zero", 10, 0, 0, true},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := mypackage.Divide(tt.a, tt.b)
            if (err != nil) != tt.wantErr {
                t.Errorf("unexpected error: %v", err)
            }
            if got != tt.want {
                t.Errorf("got %v, want %v", got, tt.want)
            }
        })
    }
}

// ベンチマーク
func BenchmarkAdd(b *testing.B) {
    b.ReportAllocs()
    for i := 0; i &lt; b.N; i++ {
        mypackage.Add(2, 3)
    }
}
</code></pre>
<h3>テスト補助</h3>
<pre><code class="language-go">// ヘルパー内の失敗を呼び出し元の行に表示する
func requireNoError(t *testing.T, err error) {
    t.Helper()
    if err != nil {
        t.Fatal(err)
    }
}

func TestWriteFile(t *testing.T) {
    t.Setenv("APP_ENV", "test") // テスト終了時に自動で元へ戻る
    dir := t.TempDir()             // テスト終了時に自動削除
    t.Cleanup(func() {
        // モックのリセットなど、任意の後始末を書く
    })

    path := filepath.Join(dir, "output.txt")
    requireNoError(t, os.WriteFile(path, []byte("hello"), 0o644))
}
</code></pre>
<pre><code class="language-bash">go test -cover ./... # カバレッジを表示
</code></pre>
<hr />
<h2>標準ライブラリ早引き</h2>
<h3>fmt</h3>
<pre><code class="language-go">// 出力
fmt.Print("no newline")
fmt.Println("with newline")
fmt.Printf("formatted %s %d %v\n", "str", 42, true)
fmt.Fprintf(os.Stderr, "error: %v\n", err)

// 文字列生成
s := fmt.Sprintf("Hello, %s!", name)
msg := fmt.Errorf("wrap: %w", err)

// 主要フォーマット動詞
// %v  デフォルト表現    %+v  フィールド名付き    %#v  Go構文表現
// %T  型名             %d  整数              %f  浮動小数点
// %s  文字列           %q  クォート文字列      %x  16進数
// %p  ポインタアドレス   %b  2進数             %e  指数表記
</code></pre>
<h3>strings</h3>
<pre><code class="language-go">import "strings"

strings.Contains("Hello", "ell")     // true
strings.HasPrefix("Hello", "He")     // true
strings.HasSuffix("Hello", "lo")     // true
strings.Count("cheese", "e")         // 3
strings.Index("Hello", "ll")         // 2
strings.Replace("oink oink", "oink", "moo", 1) // "moo oink"
strings.ReplaceAll("oink oink", "oink", "moo")  // "moo moo"
strings.ToUpper("hello")             // "HELLO"
strings.ToLower("HELLO")             // "hello"
strings.TrimSpace("  hello  ")       // "hello"
strings.Trim("##hello##", "#")       // "hello"
strings.Split("a,b,c", ",")          // ["a" "b" "c"]
strings.Join([]string{"a","b"}, "-") // "a-b"
strings.Fields("a  b\tc")            // ["a" "b" "c"]

// Builder（ループ内での大量結合に有効。単純な + は少数なら問題ない）
var sb strings.Builder
for i := 0; i &lt; 5; i++ {
    fmt.Fprintf(&amp;sb, "%d", i)
}
sb.String() // "01234"
</code></pre>
<h3>strconv</h3>
<pre><code class="language-go">import "strconv"

strconv.Itoa(42)                     // "42"
strconv.Atoi("42")                   // 42, nil
strconv.ParseFloat("3.14", 64)       // 3.14, nil
strconv.FormatFloat(3.14, 'f', 2, 64)// "3.14"
strconv.ParseBool("true")            // true, nil
strconv.FormatBool(true)             // "true"
</code></pre>
<h3>sort</h3>
<pre><code class="language-go">import "sort"

nums := []int{5, 2, 4, 1, 3}
sort.Ints(nums)                          // [1 2 3 4 5]

words := []string{"b", "a", "c"}
sort.Strings(words)

// カスタムソート
sort.Slice(nums, func(i, j int) bool {
    return nums[i] &gt; nums[j] // 降順
})
</code></pre>
<pre><code class="language-go">// slices パッケージ（Go 1.21〜、ジェネリクス版）
import (
    "cmp"
    "slices"
)
slices.Sort(nums)                                         // 昇順
idx, found := slices.BinarySearch(nums, 3)               // 昇順ソート済みに対して使う

// 降順ソート：cmp.Compare を使うと安全
slices.SortFunc(nums, func(a, b int) int { return cmp.Compare(b, a) })
</code></pre>
<h3>maps（Go 1.21〜、イテレータ API は Go 1.23〜）</h3>
<pre><code class="language-go">import (
    "maps"
    "slices"
)

m := map[string]int{"a": 1, "b": 2}
m2 := maps.Clone(m)              // コピー
maps.Copy(m2, m)                  // m の全エントリを m2 にマージ
delete(m, "a")                    // キー削除は組み込み関数
keys := slices.Collect(maps.Keys(m))   // キー一覧をスライスに
</code></pre>
<h3>time</h3>
<pre><code class="language-go">import "time"

now := time.Now()
t := time.Date(2026, 6, 1, 12, 0, 0, 0, time.Local)

// フォーマット（Go独自：2006-01-02 15:04:05 が基準時刻）
now.Format("2006-01-02 15:04:05")
now.Format(time.RFC3339) // "2026-06-22T12:00:00+09:00"
t, _ = time.Parse("2006-01-02", "2026-06-22")

// 計算
later := now.Add(24 * time.Hour)
diff := later.Sub(now) // time.Duration
fmt.Println(diff.Hours()) // 24.0

// タイマー
time.Sleep(100 * time.Millisecond)
timer := time.NewTimer(1 * time.Second)
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
</code></pre>
<h3>os / filepath</h3>
<pre><code class="language-go">import (
    "os"
    "path/filepath"
)

// ファイル読み書き
data, err := os.ReadFile("file.txt")
err = os.WriteFile("out.txt", data, 0644)

// ディレクトリ操作
entries, _ := os.ReadDir(".")
for _, e := range entries {
    fmt.Println(e.Name(), e.IsDir())
}
os.MkdirAll("a/b/c", 0755)
os.Remove("file.txt")
os.RemoveAll("dir/")

// 環境変数
home := os.Getenv("HOME")
os.Setenv("KEY", "value")

// パス操作
filepath.Join("a", "b", "c")       // OS 依存の区切り文字で結合
filepath.Base("/a/b/file.txt")      // "file.txt"
filepath.Dir("/a/b/file.txt")       // "/a/b"
filepath.Ext("file.txt")            // ".txt"
filepath.Abs("relative/path")       // 絶対パス
</code></pre>
<h3>encoding/json</h3>
<pre><code class="language-go">import "encoding/json"

type Point struct {
    X int `json:"x"`
    Y int `json:"y"`
}

// エンコード
p := Point{X: 1, Y: 2}
b, err := json.Marshal(p)          // []byte
s, err := json.MarshalIndent(p, "", "  ") // 整形

// デコード
var p2 Point
err = json.Unmarshal(b, &amp;p2)

// ストリーム
enc := json.NewEncoder(os.Stdout)
enc.Encode(p)

dec := json.NewDecoder(os.Stdin) // r は io.Reader なら何でも可
dec.Decode(&amp;p2)

// 型不明な場合
var v any
json.Unmarshal(data, &amp;v)
if m, ok := v.(map[string]any); ok {
    fmt.Println(m["key"])
}
</code></pre>
<h4>encoding/json/v2（Go 1.27〜）</h4>
<p><code>encoding/json/v2</code> は、オプションで動作を調整できる新しいJSON APIです。不正なUTF-8やJSONオブジェクト内の重複した名前を拒否するなど、従来の <code>encoding/json</code> より厳格なデフォルトを持ちます。</p>
<pre><code class="language-go">import jsonv2 "encoding/json/v2"

type Config struct {
    Port int `json:"port"`
}

data, err := jsonv2.Marshal(Config{Port: 8080})

var cfg Config
err = jsonv2.Unmarshal(
    data,
    &amp;cfg,
    jsonv2.RejectUnknownMembers(true),
)
</code></pre>
<p>従来の <code>encoding/json</code> も引き続きサポートされるため、v2への移行は必須ではありません。既存APIの動作は維持されますが、内部実装の変更によりエラーメッセージの文面が変わる場合があります。</p>
<h3>uuid（Go 1.27〜）</h3>
<pre><code class="language-go">import "uuid"

id := uuid.New()    // 用途に特定のバージョン要件がなければこちらを使用
id7 := uuid.NewV7() // 時系列で並べやすいUUID v7

parsed, err := uuid.Parse("f81d4fae-7dec-11d0-a765-00a0c91e6bf6")
if err != nil {
    log.Fatal(err)
}

fmt.Println(id, id7, parsed)
</code></pre>
<p><code>uuid.MustParse</code> は不正な文字列でpanicするため、固定値やテストでの利用に向いています。</p>
<h3>net/http</h3>
<pre><code class="language-go">import (
    "bytes"
    "context"
    "errors"
    "io"
    "log"
    "net/http"
    "os"
    "os/signal"
    "syscall"
    "time"
)

// 運用環境ではタイムアウト設定を推奨（デフォルトクライアントは timeout なし）
client := &amp;http.Client{Timeout: 10 * time.Second}

// GET
resp, err := client.Get("https://example.com")
if err != nil { return err }
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)

// カスタムリクエスト（POST など）
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonData))
if err != nil { return err }
req.Header.Set("Content-Type", "application/json")
resp2, err := client.Do(req)
if err != nil { return err }
defer resp2.Body.Close()

// HTTPサーバー
mux := http.NewServeMux()
mux.HandleFunc("GET /hello/{name}", func(w http.ResponseWriter, r *http.Request) {
    name := r.PathValue("name") // Go 1.22〜 パターンマッチ
    fmt.Fprintf(w, "Hello, %s!", name)
})

// 運用環境ではタイムアウトと graceful shutdown の設定を推奨
// タイムアウト値は、アップロードやストリーミングなどの用途に合わせて調整する
server := &amp;http.Server{
    Addr:              ":8080",
    Handler:           mux,
    ReadHeaderTimeout: 5 * time.Second,
    ReadTimeout:       30 * time.Second,
    WriteTimeout:      30 * time.Second,
    IdleTimeout:       60 * time.Second,
}
go func() {
    if err := server.ListenAndServe(); err != nil &amp;&amp; !errors.Is(err, http.ErrServerClosed) {
        log.Printf("server error: %v", err)
    }
}()

shutdownSignal, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
&lt;-shutdownSignal.Done()

shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
    log.Printf("shutdown error: %v", err)
}
</code></pre>
<h3>log/slog（Go 1.21〜 構造化ログ）</h3>
<pre><code class="language-go">import "log/slog"

// デフォルトロガー
slog.Info("server started", "port", 8080)
slog.Error("failed", "err", err)

// JSON ロガー
logger := slog.New(slog.NewJSONHandler(os.Stdout, &amp;slog.HandlerOptions{
    Level: slog.LevelDebug,
}))
logger.Info("user logged in", "userID", 42, "ip", "127.0.0.1")
// {"time":"...","level":"INFO","msg":"user logged in","userID":42,"ip":"127.0.0.1"}

// グループ
logger.With("requestID", "abc123").Info("processing")
</code></pre>
<hr />
<h2>Tips &amp; よくあるミス</h2>
<h3>goroutineリーク</h3>
<pre><code class="language-go">// NG: goroutine が永遠に待ち続ける
go func() {
    ch &lt;- result // 受信者がいないとリーク
}()

// OK: コンテキストでキャンセルを伝える
go func() {
    select {
    case ch &lt;- result:
    case &lt;-ctx.Done():
        return
    }
}()
</code></pre>
<h3>nil インターフェース</h3>
<pre><code class="language-go">// NG: *MyError が nil でも、interface は nil にならない
func getError() error {
    var err *MyError = nil
    return err // error インターフェースは non-nil！
}

if getError() != nil { // true になってしまう
    fmt.Println("this prints unexpectedly")
}

// OK
func getError() error {
    return nil // 直接 nil を返す
}
</code></pre>
<h3>スライスの容量事前確保</h3>
<pre><code class="language-go">// NG: append のたびにコピーが発生する可能性
result := []int{}
for i := 0; i &lt; 10000; i++ {
    result = append(result, i)
}

// OK: 事前に確保
result := make([]int, 0, 10000)
for i := 0; i &lt; 10000; i++ {
    result = append(result, i)
}
</code></pre>
<h3>for ループ変数のクロージャキャプチャ（Go 1.22 で修正済み）</h3>
<pre><code class="language-go">// Go 1.21 以前: 全ゴルーチンが同じ i を参照してしまう
for i := 0; i &lt; 5; i++ {
    go func() { fmt.Println(i) }() // 全部 5 になる可能性
}

// Go 1.22 以降: ループ変数がイテレーションごとに新しい変数に
// 上記コードは正しく 0,1,2,3,4 を出力する

// Go 1.21 以前の対処
for i := 0; i &lt; 5; i++ {
    i := i // シャドーイング
    go func() { fmt.Println(i) }()
}
</code></pre>
<hr />
<h2>モジュール・パッケージ管理</h2>
<pre><code class="language-bash"># モジュール初期化
go mod init github.com/yourname/yourproject

# Go 1.27
go get go@1.27

# 依存追加
go get github.com/some/package@v1.2.3

# 依存整理（不要なものを削除）
go mod tidy

# ベンダリング
go mod vendor

# 主要コマンド
go build ./...         # ビルド
go test ./...          # テスト
go test -race ./...    # レースコンディション検出
go vet ./...           # 静的解析
go fmt ./...           # フォーマット
</code></pre>
<hr />
<p>公式リファレンス：<a href="https://pkg.go.dev">pkg.go.dev</a> / <a href="https://go.dev/ref/spec">go.dev/ref/spec</a></p>
]]></content:encoded></item><item><title><![CDATA[Entity Framework Core Cheat Sheet]]></title><description><![CDATA[Practical EF Core 10 examples for .NET 10: CRUD, LINQ, relationships, migrations, and optimistic concurrency, using SQLite and SQL Server.]]></description><link>https://nobuo-miura.hashnode.dev/entity-framework-core-cheat-sheet</link><guid isPermaLink="true">https://nobuo-miura.hashnode.dev/entity-framework-core-cheat-sheet</guid><category><![CDATA[C#]]></category><category><![CDATA[entity framework]]></category><category><![CDATA[cheatsheet]]></category><dc:creator><![CDATA[Nobuo Miura]]></dc:creator><pubDate>Thu, 26 Nov 2026 12:01:56 GMT</pubDate><content:encoded><![CDATA[<p>An EF Core 10 / .NET 10 cheat sheet covering CRUD, LINQ, relationships, migrations, and concurrency with SQLite examples.</p>
<hr />
<h2>EF Core versus EF6</h2>
<p>Entity Framework is an ORM that maps .NET objects to database data. This page covers EF Core. EF6 is a separate product line; migration requires more than replacing a package.</p>
<table>
<thead>
<tr>
<th>Topic</th>
<th>EF Core</th>
<th>EF6</th>
</tr>
</thead>
<tbody><tr>
<td>Main namespace</td>
<td><code>Microsoft.EntityFrameworkCore</code></td>
<td><code>System.Data.Entity</code></td>
</tr>
<tr>
<td>Main packages</td>
<td><code>Microsoft.EntityFrameworkCore.*</code></td>
<td><code>EntityFramework</code></td>
</tr>
<tr>
<td>Model definition</td>
<td>Code and configuration; reverse engineering from an existing DB</td>
<td>Code First, EDMX designer, and other workflows</td>
</tr>
<tr>
<td>Coverage here</td>
<td>EF Core 10 / .NET 10</td>
<td>Not covered by the API examples</td>
</tr>
</tbody></table>
<p>EF Core 10 requires .NET 10. EF Core 8 and 9 target .NET 8. For an existing application, check whether its database provider supports the intended EF Core major version.</p>
<p><a href="https://learn.microsoft.com/en-us/ef/efcore-and-ef6/">Official EF6 and EF Core comparison</a> / <a href="https://learn.microsoft.com/en-us/ef/core/what-is-new/">Release information</a></p>
<hr />
<h2>Setup</h2>
<p>Create a console project using SQLite. These commands select <a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Sqlite/10.0.12">stable version 10.0.12</a> and align the Microsoft EF package and tool versions.</p>
<pre><code class="language-bash">dotnet new console -n EfCheatSheet --framework net10.0
cd EfCheatSheet
dotnet package add Microsoft.EntityFrameworkCore.Sqlite --version 10.0.12
dotnet package add Microsoft.EntityFrameworkCore.Design --version 10.0.12
dotnet new tool-manifest
dotnet tool install dotnet-ef --version 10.0.12
dotnet ef --version
</code></pre>
<p>If the repository already has a tool manifest, use <code>dotnet tool restore</code> instead of creating another. All subsequent file names and commands are relative to this project directory.</p>
<hr />
<h2>Shared model and DbContext</h2>
<p>Create <code>BlogContext.cs</code>. <code>DbContext</code> coordinates queries and change tracking; <code>DbSet&lt;T&gt;</code> is an entry point for querying and adding entities.</p>
<pre><code class="language-csharp">using Microsoft.EntityFrameworkCore;

public sealed class Blog
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public List&lt;Post&gt; Posts { get; set; } = [];
}

public sealed class Post
{
    public int Id { get; set; }
    public int BlogId { get; set; }
    public Blog Blog { get; set; } = null!;
    public string Title { get; set; } = "";
    public int Views { get; set; }
    public bool IsDeleted { get; set; }
    public Guid Version { get; set; } = Guid.NewGuid();
}

public sealed class BlogContext(DbContextOptions&lt;BlogContext&gt; options) : DbContext(options)
{
    public DbSet&lt;Blog&gt; Blogs =&gt; Set&lt;Blog&gt;();
    public DbSet&lt;Post&gt; Posts =&gt; Set&lt;Post&gt;();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity&lt;Blog&gt;(entity =&gt;
        {
            entity.Property(b =&gt; b.Name).HasMaxLength(100).IsRequired();
            entity.HasIndex(b =&gt; b.Name).IsUnique();
        });
        modelBuilder.Entity&lt;Post&gt;(entity =&gt;
        {
            entity.Property(p =&gt; p.Title).HasMaxLength(200).IsRequired();
            entity.Property(p =&gt; p.Version).IsConcurrencyToken();
            entity.HasIndex(p =&gt; new { p.BlogId, p.Id });
            entity.HasOne(p =&gt; p.Blog)
                .WithMany(b =&gt; b.Posts)
                .HasForeignKey(p =&gt; p.BlogId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasQueryFilter("SoftDelete", p =&gt; !p.IsDeleted);
        });
    }
}
</code></pre>
<p>By convention, <code>Id</code> is the primary key. <code>BlogId</code> is a foreign key; <code>Blog</code> and <code>Posts</code> are navigations. <code>null!</code> tells the compiler to expect EF to supply a value; it does not load related data automatically.</p>
<p>Settings such as <code>HasMaxLength</code> describe the database model, not EF input validation. SQLite does not enforce the string-length limit, so validate input separately. Named query filters require EF Core 10.</p>
<p><a href="https://learn.microsoft.com/en-us/ef/core/modeling/">Official modeling guide</a></p>
<hr />
<h2>Model attributes (Data Annotations)</h2>
<p>Model configuration can be placed directly on entity classes and properties. For conflicting settings, <strong>Fluent API overrides attributes, and attributes override conventions</strong>. Attributes keep simple mappings near the model; Fluent API supports more detailed configuration and separates persistence concerns from entity classes.</p>
<table>
<thead>
<tr>
<th>Attribute</th>
<th>Purpose</th>
<th>Fluent API counterpart</th>
</tr>
</thead>
<tbody><tr>
<td><code>[Table("Articles")]</code></td>
<td>Table name</td>
<td><code>ToTable("Articles")</code></td>
</tr>
<tr>
<td><code>[Column("title")]</code></td>
<td>Column name</td>
<td><code>HasColumnName("title")</code></td>
</tr>
<tr>
<td><code>[Key]</code></td>
<td>Single-property primary key</td>
<td><code>HasKey(e =&gt; e.Id)</code></td>
</tr>
<tr>
<td><code>[PrimaryKey(nameof(A), nameof(B))]</code></td>
<td>Composite key on the class (EF Core 7+)</td>
<td><code>HasKey(e =&gt; new { e.A, e.B })</code></td>
</tr>
<tr>
<td><code>[Required]</code></td>
<td>Required / non-nullable model property</td>
<td><code>IsRequired()</code></td>
</tr>
<tr>
<td><code>[MaxLength(200)]</code></td>
<td>Maximum length</td>
<td><code>HasMaxLength(200)</code></td>
</tr>
<tr>
<td><code>[StringLength(200)]</code></td>
<td>Maximum length; MinimumLength is not a DB constraint</td>
<td><code>HasMaxLength(200)</code></td>
</tr>
<tr>
<td><code>[Precision(18, 2)]</code></td>
<td>Numeric precision and scale</td>
<td><code>HasPrecision(18, 2)</code></td>
</tr>
<tr>
<td><code>[Unicode(false)]</code></td>
<td>Non-Unicode configuration (provider-dependent)</td>
<td><code>IsUnicode(false)</code></td>
</tr>
<tr>
<td><code>[Index(nameof(Code), IsUnique = true)]</code></td>
<td>Unique index on the class</td>
<td><code>HasIndex(e =&gt; e.Code).IsUnique()</code></td>
</tr>
<tr>
<td><code>[ForeignKey(nameof(BlogId))]</code></td>
<td>Foreign key for a navigation</td>
<td><code>HasForeignKey(e =&gt; e.BlogId)</code></td>
</tr>
<tr>
<td><code>[InverseProperty(nameof(Blog.Posts))]</code></td>
<td>Identify the inverse navigation</td>
<td><code>WithMany(b =&gt; b.Posts)</code></td>
</tr>
<tr>
<td><code>[NotMapped]</code></td>
<td>Exclude from mapping</td>
<td><code>Ignore(e =&gt; e.DisplayName)</code></td>
</tr>
<tr>
<td><code>[DatabaseGenerated(DatabaseGeneratedOption.Identity)]</code></td>
<td>Value generated on add</td>
<td><code>ValueGeneratedOnAdd()</code></td>
</tr>
<tr>
<td><code>[DatabaseGenerated(DatabaseGeneratedOption.Computed)]</code></td>
<td>Value generated on add and update</td>
<td><code>ValueGeneratedOnAddOrUpdate()</code></td>
</tr>
<tr>
<td><code>[ConcurrencyCheck]</code></td>
<td>Include the original value in update/delete predicates</td>
<td><code>IsConcurrencyToken()</code></td>
</tr>
<tr>
<td><code>[Timestamp]</code></td>
<td>Database generation on add/update and a concurrency token</td>
<td><code>IsRowVersion()</code></td>
</tr>
</tbody></table>
<p><code>Key</code>, <code>Required</code>, <code>MaxLength</code>, <code>StringLength</code>, <code>ConcurrencyCheck</code>, and <code>Timestamp</code> are in <code>System.ComponentModel.DataAnnotations</code>. <code>Table</code>, <code>Column</code>, <code>ForeignKey</code>, <code>InverseProperty</code>, <code>NotMapped</code>, and <code>DatabaseGenerated</code> are in its <code>.Schema</code> namespace. EF Core’s <code>PrimaryKey</code>, <code>Index</code>, <code>Precision</code>, and <code>Unicode</code> are in <code>Microsoft.EntityFrameworkCore</code>; do not confuse these with similarly named EF6 APIs.</p>
<h3>Attribute-based model example</h3>
<p>This is a separate entity declaration, not an operation to paste at the end of <code>Program.cs</code>. To use it, register <code>DbSet&lt;AnnotatedArticle&gt;</code> in a context and update its schema. It does not replace the shared <code>Blog</code> / <code>Post</code> model.</p>
<pre><code class="language-csharp">using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;

[Table("Articles")]
[Index(nameof(Code), IsUnique = true)]
public sealed class AnnotatedArticle
{
    [Key]
    public int Id { get; set; }

    [Required, MaxLength(32)]
    public string Code { get; set; } = "";

    [Column("title")]
    [Required, MaxLength(200)]
    public string Title { get; set; } = "";

    [Precision(18, 2)]
    public decimal Price { get; set; }

    [ConcurrencyCheck]
    public Guid Version { get; set; } = Guid.NewGuid();

    [NotMapped]
    public string DisplayName =&gt; $"{Code}: {Title}";
}
</code></pre>
<p><code>[ConcurrencyCheck]</code> does not generate a new value: assign a new <code>Version</code> on each protected update, just as in the shared model. <code>[DatabaseGenerated]</code> describes value generation; it does not by itself define a computed SQL expression or make every type auto-generated. Use provider-supported defaults or computed-column configuration as appropriate.</p>
<h3>Model mapping versus input validation</h3>
<p>EF Core does not run Data Annotations object validation automatically during <code>SaveChanges</code>. For example, <code>[Range]</code> and <code>[EmailAddress]</code> do not create database constraints. Validate input through <a href="http://ASP.NET">ASP.NET</a> Core validation or <code>Validator.TryValidateObject</code> as appropriate. With nullable reference types enabled, a <code>string</code> property is required by convention; <code>[Required]</code> makes that mapping explicit. C# <code>required</code> is an initialization rule, not the same feature. Database enforcement of length and precision remains provider-dependent.</p>
<p><a href="https://learn.microsoft.com/en-us/ef/core/modeling/">Model configuration</a> / <a href="https://learn.microsoft.com/en-us/ef/core/modeling/entity-properties">Property mapping</a> / <a href="https://learn.microsoft.com/en-us/ef/core/modeling/relationships/mapping-attributes">Relationship attributes</a></p>
<hr />
<h2>Minimal runnable example</h2>
<p>Replace <code>Program.cs</code> with this code. Keeping the connection open lets contexts share the in-memory SQLite database.</p>
<pre><code class="language-csharp">using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;

await using var connection = new SqliteConnection("Data Source=:memory:");
await connection.OpenAsync();
var options = new DbContextOptionsBuilder&lt;BlogContext&gt;()
    .UseSqlite(connection)
    .Options;
await using var db = new BlogContext(options);
await db.Database.EnsureCreatedAsync();

var blog = new Blog
{
    Name = "Development",
    Posts = [new Post { Title = "Hello EF Core", Views = 10 }]
};
db.Blogs.Add(blog);
await db.SaveChangesAsync();
db.ChangeTracker.Clear();

// Insert an operation example from a later section here.
Console.WriteLine(await db.Posts.CountAsync());
</code></pre>
<p>Run <code>dotnet run</code>; it prints <code>1</code>. Insert <strong>one</strong> later “operation example” at the end of this program, using the existing <code>db</code>, <code>options</code>, and <code>blog</code>. Complete-file examples are identified separately. Every run creates a fresh database, so examples do not depend on earlier operations.</p>
<p><code>EnsureCreatedAsync</code> is useful for learning and temporary databases. It neither creates migration history nor updates an existing schema. Do not mix it with migrations on the same database.</p>
<hr />
<h2>Create, read, update, and delete</h2>
<p>Operation example. For a tracked update, change the retrieved entity’s properties and call <code>SaveChangesAsync</code>.</p>
<pre><code class="language-csharp">var post = new Post { BlogId = blog.Id, Title = "Second post" };
db.Posts.Add(post);
await db.SaveChangesAsync();

var found = await db.Posts.SingleAsync(p =&gt; p.Id == post.Id);
Console.WriteLine(found.Title);
found.Title = "Updated post";
found.Version = Guid.NewGuid();
await db.SaveChangesAsync();

db.Posts.Remove(found);
await db.SaveChangesAsync();
Console.WriteLine(await db.Posts.CountAsync());
</code></pre>
<p><code>Add</code>, <code>Update</code>, and <code>Remove</code> normally change tracking state; SQL runs at <code>SaveChanges</code>. Generated keys do not automatically require <code>AddAsync</code>. <code>Update</code> can affect the state of an entire graph, so map only permitted fields rather than passing API input directly.</p>
<hr />
<h2>LINQ, projection, and aggregation</h2>
<p>Operation example. Compose expressions that EF translates to SQL, then execute them with methods such as <code>ToListAsync</code>. Use <code>Select</code> to retrieve only the fields you need.</p>
<pre><code class="language-csharp">var query = db.Posts
    .AsNoTracking()
    .Where(p =&gt; p.Views &gt;= 5)
    .OrderByDescending(p =&gt; p.Views)
    .ThenBy(p =&gt; p.Id)
    .Select(p =&gt; new { p.Id, p.Title, BlogName = p.Blog.Name });
var rows = await query.ToListAsync();
Console.WriteLine(rows[0].BlogName);
Console.WriteLine(await db.Posts.AnyAsync(p =&gt; p.Views &gt; 0));
Console.WriteLine(await db.Posts.SumAsync(p =&gt; p.Views));
Console.WriteLine(query.ToQueryString());
</code></pre>
<p>Compose filters while the query is still <code>IQueryable&lt;T&gt;</code>. Operations after <code>ToList</code> or <code>AsEnumerable</code> run in memory. Arbitrary C# methods are not necessarily translatable; untranslatable filters normally throw at execution.</p>
<hr />
<h2>Choosing a retrieval API</h2>
<p>Choose a method that matches your requirements.</p>
<table>
<thead>
<tr>
<th>API</th>
<th>Behavior</th>
</tr>
</thead>
<tbody><tr>
<td><code>FindAsync(key)</code></td>
<td>Looks for a tracked primary key first, then queries the DB</td>
</tr>
<tr>
<td><code>FirstOrDefaultAsync()</code></td>
<td>Returns the first match or the default value</td>
</tr>
<tr>
<td><code>SingleAsync()</code></td>
<td>Requires exactly one match; throws for zero or multiple matches</td>
</tr>
<tr>
<td><code>SingleOrDefaultAsync()</code></td>
<td>Returns the default for zero matches; throws for multiple</td>
</tr>
<tr>
<td><code>AnyAsync()</code></td>
<td>Checks existence</td>
</tr>
<tr>
<td><code>CountAsync()</code></td>
<td>Returns a count</td>
</tr>
<tr>
<td><code>ToListAsync()</code></td>
<td>Materializes results in memory</td>
</tr>
</tbody></table>
<p>Use <code>OrderBy</code> to define “first.” <code>FindAsync</code> may return an already tracked entity, so it does not always retrieve fresh database state.</p>
<hr />
<h2>Change tracking and AsNoTracking</h2>
<p>Operation example. Use <code>AsNoTracking</code> for read-only queries. Changes to an untracked entity are not saved automatically.</p>
<pre><code class="language-csharp">var detached = await db.Posts.AsNoTracking().SingleAsync();
detached.Title = "Not saved";
Console.WriteLine(db.Entry(detached).State);
Console.WriteLine(await db.SaveChangesAsync());

var tracked = await db.Posts.SingleAsync();
tracked.Title = "Saved";
tracked.Version = Guid.NewGuid();
await db.SaveChangesAsync();
</code></pre>
<p>A context generally tracks only one instance per primary key. <code>AsNoTrackingWithIdentityResolution</code> reuses instances for repeated keys within the result, without tracking them for updates in the context.</p>
<hr />
<h2>Loading related data</h2>
<p>Operation example. <code>Include</code> loads related entities. If a projection only needs related values, reference them in <code>Select</code>; no <code>Include</code> is needed.</p>
<pre><code class="language-csharp">var blogs = await db.Blogs
    .AsNoTracking()
    .Include(b =&gt; b.Posts.Where(p =&gt; p.Views &gt;= 5))
    .AsSplitQuery()
    .ToListAsync();
Console.WriteLine(blogs[0].Posts.Count);

var one = await db.Blogs.SingleAsync();
await db.Entry(one).Collection(b =&gt; b.Posts).LoadAsync();
Console.WriteLine(one.Posts.Count);
</code></pre>
<p>Use <code>ThenInclude</code> for additional relationship levels. <code>AsSplitQuery</code> loads collections with separate queries to reduce JOIN row multiplication, but adds round trips and may observe inconsistent data during concurrent updates.</p>
<p>With tracking, filtered Include may contain related entities tracked earlier, even if they fail the filter. Lazy loading requires additional configuration and may cause N+1 queries when navigations are accessed in a loop.</p>
<p><a href="https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager">Official eager-loading guide</a></p>
<hr />
<h2>Pagination</h2>
<p>Operation example. Offset pagination suits page-number navigation; keyset pagination suits moving to the next page. Use a unique ordering.</p>
<pre><code class="language-csharp">int pageSize = 20;
int pageNumber = 1;
var page = await db.Posts.AsNoTracking()
    .OrderBy(p =&gt; p.Id)
    .Skip((pageNumber - 1) * pageSize)
    .Take(pageSize)
    .ToListAsync();

int lastId = 0;
var next = await db.Posts.AsNoTracking()
    .Where(p =&gt; p.Id &gt; lastId)
    .OrderBy(p =&gt; p.Id)
    .Take(pageSize)
    .ToListAsync();
Console.WriteLine($"{page.Count}, {next.Count}");
</code></pre>
<p>For the actual next page, supply the previous page’s last <code>Id</code>. If ordering by multiple columns, include all ordering columns in the cursor predicate. Cap page size and consider indexes matching the filter and ordering.</p>
<hr />
<h2>Set-based updates and deletes</h2>
<p>Operation example. <code>ExecuteUpdateAsync</code> and <code>ExecuteDeleteAsync</code> are relational APIs introduced in EF Core 7. They execute SQL directly without loading entities.</p>
<pre><code class="language-csharp">int updated = await db.Posts.Where(p =&gt; p.Views &lt; 100)
    .ExecuteUpdateAsync(setters =&gt; setters.SetProperty(p =&gt; p.Views, p =&gt; p.Views + 1));
int deleted = await db.Posts.Where(p =&gt; p.Views == 0).ExecuteDeleteAsync();
Console.WriteLine($"{updated}, {deleted}");
</code></pre>
<p>No <code>SaveChanges</code> call is needed. The change tracker is not synchronized; reload or otherwise reconcile state before mixing with tracked updates of the same rows. Calls are separate operations and do not automatically share one transaction. Concurrency tokens are neither checked nor updated automatically.</p>
<p><a href="https://learn.microsoft.com/en-us/ef/core/saving/execute-insert-update-delete">Official ExecuteUpdate / ExecuteDelete guide</a></p>
<hr />
<h2>Transactions</h2>
<p>Operation example. When supported by the provider, one <code>SaveChanges</code> call runs in a transaction by default. Use an explicit transaction to group multiple saves or direct SQL operations.</p>
<pre><code class="language-csharp">await using var transaction = await db.Database.BeginTransactionAsync();
try
{
    db.Blogs.Add(new Blog { Name = "Transactions" });
    await db.SaveChangesAsync();
    await db.Posts.ExecuteUpdateAsync(s =&gt; s.SetProperty(p =&gt; p.Views, p =&gt; p.Views + 1));
    await transaction.CommitAsync();
}
catch
{
    await transaction.RollbackAsync();
    throw;
}
</code></pre>
<p>Rolling back does not restore tracked objects’ values. Recreate the context where appropriate. With a retrying execution strategy, the entire explicit transaction must be coordinated as one retriable unit.</p>
<hr />
<h2>Optimistic concurrency</h2>
<p>Operation example. The shared model’s <code>Version</code> detects a preceding update by another context. SQLite has no SQL Server-style <code>rowversion</code>, so this example updates the token in application code.</p>
<pre><code class="language-csharp">await using var other = new BlogContext(options);
var mine = await db.Posts.SingleAsync();
var theirs = await other.Posts.SingleAsync();

theirs.Title = "Changed elsewhere";
theirs.Version = Guid.NewGuid();
await other.SaveChangesAsync();

mine.Title = "My change";
mine.Version = Guid.NewGuid();
try
{
    await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
    await db.Entry(mine).ReloadAsync();
    Console.WriteLine(mine.Title);
}
</code></pre>
<p>This example discards the local edit and reloads. In an application, choose a policy such as notifying the user, merging values, or conditionally retrying. Update the token on every write path it is intended to protect.</p>
<p><a href="https://learn.microsoft.com/en-us/ef/core/saving/concurrency">Official concurrency guide</a></p>
<h3>SQL Server: rowversion and [Timestamp]</h3>
<p>SQL Server’s <code>rowversion</code> is an automatically generated 8-byte binary value used for optimistic concurrency. Despite the attribute name <code>[Timestamp]</code>, it is <strong>not a date or time</strong>. <code>RowVersion</code> is simply a property name; <code>[Timestamp]</code> or <code>.IsRowVersion()</code> supplies the configuration.</p>
<p>The following declarations are <strong>for SQL Server</strong>, separate from the SQLite sample. Add <code>Microsoft.EntityFrameworkCore.SqlServer</code> 10.0.12, construct the context options with <code>UseSqlServer(connectionString)</code>, and create the SQL Server schema with migrations. Obtain the connection string from configuration.</p>
<pre><code class="language-csharp">using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;

public sealed class SqlServerDocument
{
    public int Id { get; set; }
    [MaxLength(200)]
    public string Title { get; set; } = "";

    [Timestamp]
    public byte[] RowVersion { get; set; } = [];
}

public sealed class SqlServerContext(DbContextOptions&lt;SqlServerContext&gt; options)
    : DbContext(options)
{
    public DbSet&lt;SqlServerDocument&gt; Documents =&gt; Set&lt;SqlServerDocument&gt;();
}
</code></pre>
<p>SQL Server generates a new token on insert and on each update of the row, even if an update writes the same values. EF uses the original token along with the key in tracked update/delete predicates. If another writer changed or deleted the row, zero affected rows result in <code>DbUpdateConcurrencyException</code>. After a successful save, EF reads back the generated token; do not assign a new token yourself.</p>
<table>
<thead>
<tr>
<th>Choice</th>
<th>Value generation</th>
<th>Typical use</th>
</tr>
</thead>
<tbody><tr>
<td><code>[Timestamp]</code> / <code>IsRowVersion()</code></td>
<td>Database-generated</td>
<td>SQL Server <code>byte[]</code> / <code>rowversion</code></td>
</tr>
<tr>
<td><code>[ConcurrencyCheck]</code> / <code>IsConcurrencyToken()</code></td>
<td>Not configured by this setting</td>
<td>Application-managed <code>Guid</code> or other property</td>
</tr>
</tbody></table>
<p>SQLite does not gain automatic rowversion generation from <code>[Timestamp]</code>; use the application-managed token shown earlier. <code>ExecuteUpdate</code> and <code>ExecuteDelete</code> bypass EF’s automatic concurrency handling. For these APIs, explicitly filter on the original token and check the affected-row count.</p>
<h3>Updates from an API or edit form</h3>
<p>Round-trip the token from when the user opened the record, for example as Base64, and restore it to <code>byte[]</code>. If you only reload the latest row when saving, you can miss changes made while the user was editing. The following helper belongs in its own file alongside the SQL Server declarations above.</p>
<pre><code class="language-csharp">using Microsoft.EntityFrameworkCore;

public static class DocumentUpdates
{
    public static async Task&lt;byte[]&gt; UpdateTitleAsync(
        SqlServerContext db, int id, string title, byte[] originalRowVersion,
        CancellationToken cancellationToken = default)
    {
        var document = await db.Documents.SingleAsync(d =&gt; d.Id == id, cancellationToken);
        db.Entry(document).Property(d =&gt; d.RowVersion).OriginalValue = originalRowVersion;
        document.Title = title;
        await db.SaveChangesAsync(cancellationToken);
        return document.RowVersion;
    }
}
</code></pre>
<p>This helper returns the new token after saving. The caller must validate the request and enforce authorization, distinguish a missing row from a concurrency conflict, and handle <code>DbUpdateConcurrencyException</code> with a policy such as HTTP 409 or asking the user to reload. With no detected property change, <code>SaveChanges</code> sends no UPDATE and therefore performs no concurrency check. After a conflict, resolve or discard the context rather than blindly retrying.</p>
<p><a href="https://learn.microsoft.com/en-us/ef/core/saving/concurrency">EF Core concurrency</a> / <a href="https://learn.microsoft.com/en-us/sql/t-sql/data-types/rowversion-transact-sql">SQL Server rowversion</a></p>
<hr />
<h2>Soft deletion and query filters</h2>
<p>Operation example. The shared model’s named filter excludes posts whose <code>IsDeleted</code> is true from ordinary queries.</p>
<pre><code class="language-csharp">var post = await db.Posts.SingleAsync();
post.IsDeleted = true;
post.Version = Guid.NewGuid();
await db.SaveChangesAsync();
Console.WriteLine(await db.Posts.CountAsync());
var all = await db.Posts.IgnoreQueryFilters(["SoftDelete"]).ToListAsync();
Console.WriteLine(all.Count);
</code></pre>
<p>Filters do not turn <code>Remove</code> into a soft delete; you must set the deletion flag. Parameterless <code>IgnoreQueryFilters()</code> disables all filters. Do not treat filters alone as an authorization boundary.</p>
<p><a href="https://learn.microsoft.com/en-us/ef/core/querying/filters">Official global query filters guide</a></p>
<hr />
<h2>Using SQL directly</h2>
<p>Operation example. Passing an interpolated string directly to <code>FromSql</code> sends the interpolated values as parameters.</p>
<pre><code class="language-csharp">string title = "Hello EF Core";
var posts = await db.Posts
    .FromSql($"SELECT * FROM Posts WHERE Title = {title}")
    .AsNoTracking()
    .ToListAsync();
Console.WriteLine(posts.Count);
</code></pre>
<p>Do not concatenate external input into <code>FromSqlRaw</code>. Identifiers such as column names cannot be parameterized; choose dynamic identifiers from an allowlist. SQL returning an entity must provide its mapped columns.</p>
<p><a href="https://learn.microsoft.com/en-us/ef/core/querying/sql-queries">Official SQL query guide</a></p>
<hr />
<h2>Migrations</h2>
<p>The following workflow uses a separate file database, <code>blog.db</code>. Add <code>BlogContextFactory.cs</code>. A design-time factory lets the tools create a context without running the learning-oriented <code>Program.cs</code>.</p>
<pre><code class="language-csharp">using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;

public sealed class BlogContextFactory : IDesignTimeDbContextFactory&lt;BlogContext&gt;
{
    public BlogContext CreateDbContext(string[] args)
    {
        var options = new DbContextOptionsBuilder&lt;BlogContext&gt;()
            .UseSqlite("Data Source=blog.db")
            .Options;
        return new BlogContext(options);
    }
}
</code></pre>
<p>If the application should use <code>blog.db</code>, configure that same database at runtime. The learning-oriented <code>Program.cs</code> above continues to use an in-memory DB. Obtain credentials from configuration or secret storage instead of embedding them in source.</p>
<h3>Create, apply, and inspect SQL</h3>
<p>Run these commands in the project directory. <code>database update</code> modifies the learning database selected by the factory above.</p>
<pre><code class="language-bash">dotnet ef migrations add InitialCreate --context BlogContext
dotnet ef migrations list --context BlogContext
dotnet ef migrations script 0 InitialCreate --output migration.sql --context BlogContext
dotnet ef database update --context BlogContext
dotnet ef migrations has-pending-model-changes --context BlogContext
</code></pre>
<p>After changing the model, add another migration with a descriptive name. Review generated code and SQL before applying it. Use <code>dotnet ef migrations remove --context BlogContext</code> to remove the last unapplied migration; do not merely delete files for an applied migration.</p>
<p>Apply reviewed SQL or migration bundles as part of production deployment. SQLite does not support <code>--idempotent</code> scripts; specify the start and end migration as shown above.</p>
<p><a href="https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/applying">Official migration deployment guide</a> / <a href="https://learn.microsoft.com/en-us/ef/core/providers/sqlite/limitations">SQLite limitations</a></p>
<hr />
<h2>Reverse engineering an existing database</h2>
<p>This example generates a model from the migrated <code>blog.db</code> into a separate output directory.</p>
<pre><code class="language-bash">dotnet ef dbcontext scaffold "Data Source=blog.db" Microsoft.EntityFrameworkCore.Sqlite --output-dir Scaffolded --context ReverseContext --no-onconfiguring
</code></pre>
<p>Review generated code before use. Reverse engineering recovers schema information, not intent such as query filters or application-managed concurrency tokens. With <code>--no-onconfiguring</code>, supply connection configuration at runtime.</p>
<hr />
<h2>DbContext lifetime and async operations</h2>
<p>Use a <code>DbContext</code> for a short unit of work and dispose it afterward. Do not share an instance across threads or overlapping asynchronous operations.</p>
<ul>
<li><a href="http://ASP.NET">ASP.NET</a> Core’s <code>AddDbContext</code> registers a scoped service by default, commonly used per request.</li>
<li>Consider <code>IDbContextFactory&lt;T&gt;</code> when DI scope and unit of work differ, such as background jobs. The caller must dispose contexts it creates.</li>
<li>Do not run queries on the same context concurrently with <code>Task.WhenAll</code>. Use separate contexts for parallel operations.</li>
<li>Pass cancellation tokens to APIs such as <code>ToListAsync(cancellationToken)</code> and <code>SaveChangesAsync(cancellationToken)</code>. Cancellation support also depends on the provider.</li>
<li>SQLite’s async APIs execute synchronously because of underlying limitations, so this example does not establish async performance on other databases.</li>
</ul>
<p><a href="https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/">Official DbContext configuration and lifetime guide</a> / <a href="https://learn.microsoft.com/en-us/dotnet/standard/data/sqlite/async">SQLite async limitations</a></p>
<hr />
<h2>SQL inspection and performance checks</h2>
<p>Operation example. <code>ToQueryString</code> inspects SQL without executing the query. Also inspect execution logs and database query plans to understand actual SQL and timings.</p>
<pre><code class="language-csharp">var query = db.Posts
    .TagWith("Posts list")
    .AsNoTracking()
    .Where(p =&gt; p.BlogId == blog.Id)
    .OrderBy(p =&gt; p.Id)
    .Take(20);
Console.WriteLine(query.ToQueryString());
</code></pre>
<ul>
<li>Project only needed columns and avoid unbounded result sets.</li>
<li>Check for N+1 queries, unnecessary Includes, large JOIN results, and deep offset pagination.</li>
<li><code>EnableSensitiveDataLogging</code> includes values in logs. Restrict it to development scenarios that need it.</li>
<li>Use execution plans to evaluate indexes; API names alone do not determine performance.</li>
</ul>
<hr />
<h2>Testing</h2>
<p>Operation example. Read back through a separate context after saving so the check is not limited to tracked objects.</p>
<pre><code class="language-csharp">db.Posts.Add(new Post { BlogId = blog.Id, Title = "Persistence test" });
await db.SaveChangesAsync();
await using var verification = new BlogContext(options);
var saved = await verification.Posts.AsNoTracking()
    .SingleAsync(p =&gt; p.Title == "Persistence test");
if (saved.Id &lt;= 0 || saved.BlogId != blog.Id)
    throw new InvalidOperationException("Persistence check failed.");
Console.WriteLine("Persistence check passed.");
</code></pre>
<p>This minimal executable check signals failure by throwing. In a test project, replace it with assertions from a framework such as MSTest.</p>
<p>In-memory SQLite can exercise relational constraints and some SQL behavior, but does not replace production SQL Server or PostgreSQL. Test important queries, collations, transactions, and migrations against the production database engine too. EF Core’s InMemory provider does not reproduce relational database behavior.</p>
<p><a href="https://learn.microsoft.com/en-us/ef/core/testing/choosing-a-testing-strategy">Official testing strategy guide</a></p>
<hr />
<h2>Version and provider differences</h2>
<p>The examples on this page assume the EF Core 10 SQLite provider.</p>
<table>
<thead>
<tr>
<th>Feature or task</th>
<th>Notes</th>
</tr>
</thead>
<tbody><tr>
<td>Set-based updates and deletes</td>
<td><code>ExecuteUpdate</code> / <code>ExecuteDelete</code> require EF Core 7 or later</td>
</tr>
<tr>
<td>Named query filters</td>
<td>Require EF Core 10; older versions combine conditions with <code>&amp;&amp;</code> in one filter</td>
</tr>
<tr>
<td>SQL Server concurrency</td>
<td>Can use database-generated <code>rowversion</code>; do not reuse that configuration for SQLite</td>
</tr>
<tr>
<td>String lengths and numeric precision</td>
<td>Constraints, types, and translatable operations vary by database</td>
</tr>
<tr>
<td>SQLite schema changes</td>
<td>Some operations rebuild tables; schemas and sequences are unsupported</td>
</tr>
<tr>
<td>Providers</td>
<td>SQL Server uses <code>UseSqlServer</code>, SQLite uses <code>UseSqlite</code>, and Npgsql uses <code>UseNpgsql</code>; each needs its provider package</td>
</tr>
</tbody></table>
<p>Check breaking changes and provider compatibility before major upgrades. These examples do not establish query translation or behavior for other providers.</p>
<p><a href="https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-10.0/whatsnew">What’s new in EF Core 10</a> / <a href="https://learn.microsoft.com/en-us/ef/core/providers/">Provider list</a></p>
<hr />
<h2>Related material</h2>
<p><a href="https://learn.microsoft.com/en-us/ef/core/">Official EF Core documentation</a></p>
]]></content:encoded></item><item><title><![CDATA[Entity Framework Core チートシート]]></title><description><![CDATA[EF Core 10・.NET 10の実用チートシート。CRUD、LINQ、関連データの読み込み、マイグレーション、楽観的同時実行制御を、SQLiteのコード例とSQL Serverのrowversionで解説します。]]></description><link>https://nobuo-miura.hashnode.dev/entity-framework-core-cheat-sheet-ja</link><guid isPermaLink="true">https://nobuo-miura.hashnode.dev/entity-framework-core-cheat-sheet-ja</guid><category><![CDATA[cheatsheet]]></category><category><![CDATA[C#]]></category><category><![CDATA[entity framework]]></category><dc:creator><![CDATA[Nobuo Miura]]></dc:creator><pubDate>Thu, 26 Nov 2026 12:00:29 GMT</pubDate><content:encoded><![CDATA[<p>EF Core 10・.NET 10をベースに、CRUD、LINQ、関連データ、マイグレーション、同時実行制御をSQLiteの例でまとめたチートシートです。</p>
<hr />
<h2>EF CoreとEF6の違い</h2>
<p>Entity Frameworkは.NETのオブジェクトとデータベースを対応付けるORMです。このページはEF Coreを対象にします。EF6は別の製品系列で、パッケージを置き換えるだけでは移行できません。</p>
<table>
<thead>
<tr>
<th>項目</th>
<th>EF Core</th>
<th>EF6</th>
</tr>
</thead>
<tbody><tr>
<td>主な名前空間</td>
<td><code>Microsoft.EntityFrameworkCore</code></td>
<td><code>System.Data.Entity</code></td>
</tr>
<tr>
<td>主なパッケージ</td>
<td><code>Microsoft.EntityFrameworkCore.*</code></td>
<td><code>EntityFramework</code></td>
</tr>
<tr>
<td>モデル定義</td>
<td>コードと設定。既存DBからコード生成も可能</td>
<td>Code First、EDMXデザイナーなど</td>
</tr>
<tr>
<td>本ページの対象</td>
<td>EF Core 10 / .NET 10</td>
<td>API例の対象外</td>
</tr>
</tbody></table>
<p>EF Core <a href="http://xn--10-4b4a.NET">10は.NET</a> 10を必要とします。EF Core 8・<a href="http://xn--9-ibu.NET">9は.NET</a> 8を対象にした系列です。既存アプリでは、使用するDBプロバイダーが対象のEF Coreメジャーバージョンをサポートしているか確認します。</p>
<p><a href="https://learn.microsoft.com/en-us/ef/efcore-and-ef6/">公式 — EF6とEF Coreの比較</a> / <a href="https://learn.microsoft.com/en-us/ef/core/what-is-new/">リリース情報</a></p>
<hr />
<h2>セットアップ</h2>
<p>SQLiteのコンソールプロジェクトを作ります。ここでは<a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Sqlite/10.0.12">安定版10.0.12</a>を指定し、Microsoft製EFパッケージとツールのバージョンを揃えます。</p>
<pre><code class="language-bash">dotnet new console -n EfCheatSheet --framework net10.0
cd EfCheatSheet
dotnet package add Microsoft.EntityFrameworkCore.Sqlite --version 10.0.12
dotnet package add Microsoft.EntityFrameworkCore.Design --version 10.0.12
dotnet new tool-manifest
dotnet tool install dotnet-ef --version 10.0.12
dotnet ef --version
</code></pre>
<p>既存リポジトリでツールマニフェストがある場合は、新規作成せず <code>dotnet tool restore</code> を使います。以降のファイルとコマンドは、このプロジェクトのディレクトリを基準にします。</p>
<hr />
<h2>共通モデル・DbContext</h2>
<p><code>BlogContext.cs</code> を作成します。<code>DbContext</code> はDBへの問い合わせと変更追跡を担当し、<code>DbSet&lt;T&gt;</code> はエンティティの問い合わせ・追加などの入口です。</p>
<pre><code class="language-csharp">using Microsoft.EntityFrameworkCore;

public sealed class Blog
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public List&lt;Post&gt; Posts { get; set; } = [];
}

public sealed class Post
{
    public int Id { get; set; }
    public int BlogId { get; set; }
    public Blog Blog { get; set; } = null!;
    public string Title { get; set; } = "";
    public int Views { get; set; }
    public bool IsDeleted { get; set; }
    public Guid Version { get; set; } = Guid.NewGuid();
}

public sealed class BlogContext(DbContextOptions&lt;BlogContext&gt; options) : DbContext(options)
{
    public DbSet&lt;Blog&gt; Blogs =&gt; Set&lt;Blog&gt;();
    public DbSet&lt;Post&gt; Posts =&gt; Set&lt;Post&gt;();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity&lt;Blog&gt;(entity =&gt;
        {
            entity.Property(b =&gt; b.Name).HasMaxLength(100).IsRequired();
            entity.HasIndex(b =&gt; b.Name).IsUnique();
        });
        modelBuilder.Entity&lt;Post&gt;(entity =&gt;
        {
            entity.Property(p =&gt; p.Title).HasMaxLength(200).IsRequired();
            entity.Property(p =&gt; p.Version).IsConcurrencyToken();
            entity.HasIndex(p =&gt; new { p.BlogId, p.Id });
            entity.HasOne(p =&gt; p.Blog)
                .WithMany(b =&gt; b.Posts)
                .HasForeignKey(p =&gt; p.BlogId)
                .OnDelete(DeleteBehavior.Cascade);
            entity.HasQueryFilter("SoftDelete", p =&gt; !p.IsDeleted);
        });
    }
}
</code></pre>
<p><code>Id</code> は規約によって主キーになります。<code>BlogId</code> は外部キー、<code>Blog</code> / <code>Posts</code> はナビゲーションです。<code>null!</code> はEFによる設定を想定したコンパイラーへの指定で、関連データを自動ロードしません。</p>
<p><code>HasMaxLength</code> などはDBのモデル設定です。EF自体の入力検証ではなく、SQLiteでは文字列長の上限も強制されないため、入力検証を別途行います。名前付きクエリフィルターはEF Core 10の機能です。</p>
<p><a href="https://learn.microsoft.com/en-us/ef/core/modeling/">公式 — モデルの作成</a></p>
<hr />
<h2>モデルの属性（Data Annotations）</h2>
<p>モデルのクラスやプロパティに属性を付けて設定できます。同じ設定が競合する場合の優先順位は <strong>Fluent API &gt; 属性 &gt; 規約</strong> です。単純なマッピングは属性でモデルの近くに書け、複雑な設定や永続化設定の分離にはFluent APIが向いています。</p>
<table>
<thead>
<tr>
<th>属性</th>
<th>用途</th>
<th>対応するFluent API</th>
</tr>
</thead>
<tbody><tr>
<td><code>[Table("Articles")]</code></td>
<td>テーブル名</td>
<td><code>ToTable("Articles")</code></td>
</tr>
<tr>
<td><code>[Column("title")]</code></td>
<td>列名</td>
<td><code>HasColumnName("title")</code></td>
</tr>
<tr>
<td><code>[Key]</code></td>
<td>単一プロパティの主キー</td>
<td><code>HasKey(e =&gt; e.Id)</code></td>
</tr>
<tr>
<td><code>[PrimaryKey(nameof(A), nameof(B))]</code></td>
<td>クラスに付ける複合主キー（EF Core 7以降）</td>
<td><code>HasKey(e =&gt; new { e.A, e.B })</code></td>
</tr>
<tr>
<td><code>[Required]</code></td>
<td>NULLを許可しないモデル設定</td>
<td><code>IsRequired()</code></td>
</tr>
<tr>
<td><code>[MaxLength(200)]</code></td>
<td>最大長</td>
<td><code>HasMaxLength(200)</code></td>
</tr>
<tr>
<td><code>[StringLength(200)]</code></td>
<td>最大長。MinimumLengthはDB制約にならない</td>
<td><code>HasMaxLength(200)</code></td>
</tr>
<tr>
<td><code>[Precision(18, 2)]</code></td>
<td>数値の精度・スケール</td>
<td><code>HasPrecision(18, 2)</code></td>
</tr>
<tr>
<td><code>[Unicode(false)]</code></td>
<td>非Unicode設定（プロバイダー依存）</td>
<td><code>IsUnicode(false)</code></td>
</tr>
<tr>
<td><code>[Index(nameof(Code), IsUnique = true)]</code></td>
<td>クラスに付ける一意インデックス</td>
<td><code>HasIndex(e =&gt; e.Code).IsUnique()</code></td>
</tr>
<tr>
<td><code>[ForeignKey(nameof(BlogId))]</code></td>
<td>ナビゲーションに対応する外部キー</td>
<td><code>HasForeignKey(e =&gt; e.BlogId)</code></td>
</tr>
<tr>
<td><code>[InverseProperty(nameof(Blog.Posts))]</code></td>
<td>対となるナビゲーションを特定</td>
<td><code>WithMany(b =&gt; b.Posts)</code></td>
</tr>
<tr>
<td><code>[NotMapped]</code></td>
<td>マッピングから除外</td>
<td><code>Ignore(e =&gt; e.DisplayName)</code></td>
</tr>
<tr>
<td><code>[DatabaseGenerated(DatabaseGeneratedOption.Identity)]</code></td>
<td>追加時に値を生成</td>
<td><code>ValueGeneratedOnAdd()</code></td>
</tr>
<tr>
<td><code>[DatabaseGenerated(DatabaseGeneratedOption.Computed)]</code></td>
<td>追加・更新時に値を生成</td>
<td><code>ValueGeneratedOnAddOrUpdate()</code></td>
</tr>
<tr>
<td><code>[ConcurrencyCheck]</code></td>
<td>元の値を更新・削除条件に含める</td>
<td><code>IsConcurrencyToken()</code></td>
</tr>
<tr>
<td><code>[Timestamp]</code></td>
<td>追加・更新時のDB生成と並行性トークン</td>
<td><code>IsRowVersion()</code></td>
</tr>
</tbody></table>
<p><code>Key</code>、<code>Required</code>、<code>MaxLength</code>、<code>StringLength</code>、<code>ConcurrencyCheck</code>、<code>Timestamp</code> は <code>System.ComponentModel.DataAnnotations</code>、<code>Table</code>、<code>Column</code>、<code>ForeignKey</code>、<code>InverseProperty</code>、<code>NotMapped</code>、<code>DatabaseGenerated</code> はその <code>.Schema</code> 名前空間にあります。EF Coreの <code>PrimaryKey</code>、<code>Index</code>、<code>Precision</code>、<code>Unicode</code> は <code>Microsoft.EntityFrameworkCore</code> にあり、EF6の同名・類似APIとは区別します。</p>
<h3>属性を使ったモデル例</h3>
<p>以下は別のエンティティの宣言例で、<code>Program.cs</code> 末尾に挿入する操作例ではありません。使用する場合はコンテキストに <code>DbSet&lt;AnnotatedArticle&gt;</code> を登録し、スキーマを更新します。共通の <code>Blog</code> / <code>Post</code> モデルを置き換えるものではありません。</p>
<pre><code class="language-csharp">using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;

[Table("Articles")]
[Index(nameof(Code), IsUnique = true)]
public sealed class AnnotatedArticle
{
    [Key]
    public int Id { get; set; }

    [Required, MaxLength(32)]
    public string Code { get; set; } = "";

    [Column("title")]
    [Required, MaxLength(200)]
    public string Title { get; set; } = "";

    [Precision(18, 2)]
    public decimal Price { get; set; }

    [ConcurrencyCheck]
    public Guid Version { get; set; } = Guid.NewGuid();

    [NotMapped]
    public string DisplayName =&gt; $"{Code}: {Title}";
}
</code></pre>
<p><code>[ConcurrencyCheck]</code> は値を自動生成しません。共通モデルと同様に、保護したい更新で <code>Version</code> を新しく設定します。<code>[DatabaseGenerated]</code> は値生成の設定であり、それだけで計算列のSQL式を定義したり、全ての型を自動採番にしたりはできません。必要に応じてDBが対応する既定値・計算列の設定を使います。</p>
<h3>モデル設定と入力検証の違い</h3>
<p>EF Coreの <code>SaveChanges</code> は、Data Annotationsによるオブジェクト検証を自動実行しません。例えば <code>[Range]</code> や <code>[EmailAddress]</code> を付けてもDB制約は作られません。<a href="http://ASP.NET">ASP.NET</a> Coreの検証や <code>Validator.TryValidateObject</code> などで入力を検証します。Nullable参照型が有効なら <code>string</code> は規約で必須となり、<code>[Required]</code> はそのモデル設定を明示できます。C#の <code>required</code> は初期化時のルールで、別の機能です。長さ・精度のDBでの強制はプロバイダーにも依存します。</p>
<p><a href="https://learn.microsoft.com/en-us/ef/core/modeling/">モデル設定</a> / <a href="https://learn.microsoft.com/en-us/ef/core/modeling/entity-properties">プロパティのマッピング</a> / <a href="https://learn.microsoft.com/en-us/ef/core/modeling/relationships/mapping-attributes">関連の属性設定</a></p>
<hr />
<h2>最小の実行例</h2>
<p><code>Program.cs</code> を以下で置き換えます。接続を開いたままにすることで、インメモリSQLiteをコンテキスト間で共有できます。</p>
<pre><code class="language-csharp">using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;

await using var connection = new SqliteConnection("Data Source=:memory:");
await connection.OpenAsync();
var options = new DbContextOptionsBuilder&lt;BlogContext&gt;()
    .UseSqlite(connection)
    .Options;
await using var db = new BlogContext(options);
await db.Database.EnsureCreatedAsync();

var blog = new Blog
{
    Name = "Development",
    Posts = [new Post { Title = "Hello EF Core", Views = 10 }]
};
db.Blogs.Add(blog);
await db.SaveChangesAsync();
db.ChangeTracker.Clear();

// 以下に各節の操作例を挿入します。
Console.WriteLine(await db.Posts.CountAsync());
</code></pre>
<p><code>dotnet run</code> で実行すると <code>1</code> が表示されます。以降の「操作例」は、このコード末尾に<strong>1つずつ</strong>挿入して試します（宣言済みの <code>db</code>、<code>options</code>、<code>blog</code> を使います）。ファイル全体の例は別途明記します。各実行で新しいDBが作られるため、例を順番に実行した状態には依存しません。</p>
<p><code>EnsureCreatedAsync</code> は学習用・一時DB向けです。マイグレーション履歴を作らず、既存スキーマを更新しません。後述のマイグレーションとは同じDBで混用しません。</p>
<hr />
<h2>追加・取得・更新・削除（CRUD）</h2>
<p>操作例です。通常の更新では、取得したエンティティのプロパティを変更して <code>SaveChangesAsync</code> を呼びます。</p>
<pre><code class="language-csharp">var post = new Post { BlogId = blog.Id, Title = "Second post" };
db.Posts.Add(post);
await db.SaveChangesAsync();

var found = await db.Posts.SingleAsync(p =&gt; p.Id == post.Id);
Console.WriteLine(found.Title);
found.Title = "Updated post";
found.Version = Guid.NewGuid();
await db.SaveChangesAsync();

db.Posts.Remove(found);
await db.SaveChangesAsync();
Console.WriteLine(await db.Posts.CountAsync());
</code></pre>
<p><code>Add</code> / <code>Update</code> / <code>Remove</code> は通常、追跡状態を変更し、SQLの実行は <code>SaveChanges</code> 時です。自動生成キーを使う場合でも、<code>AddAsync</code> が常に必要なわけではありません。<code>Update</code> はグラフ全体の状態を変更し得るため、API入力をそのまま渡さず、許可した項目だけ反映します。</p>
<hr />
<h2>LINQ・射影・集約</h2>
<p>操作例です。SQLへ変換する式を組み立て、<code>ToListAsync</code> などで実行します。必要な列だけを取得するには <code>Select</code> を使います。</p>
<pre><code class="language-csharp">var query = db.Posts
    .AsNoTracking()
    .Where(p =&gt; p.Views &gt;= 5)
    .OrderByDescending(p =&gt; p.Views)
    .ThenBy(p =&gt; p.Id)
    .Select(p =&gt; new { p.Id, p.Title, BlogName = p.Blog.Name });
var rows = await query.ToListAsync();
Console.WriteLine(rows[0].BlogName);
Console.WriteLine(await db.Posts.AnyAsync(p =&gt; p.Views &gt; 0));
Console.WriteLine(await db.Posts.SumAsync(p =&gt; p.Views));
Console.WriteLine(query.ToQueryString());
</code></pre>
<p><code>IQueryable&lt;T&gt;</code> のまま条件を組み立てます。<code>ToList</code> や <code>AsEnumerable</code> より後の処理はメモリ上で行われます。任意のC#メソッドがSQLに変換できるわけではなく、変換不能な条件は通常、実行時に例外になります。</p>
<hr />
<h2>取得APIの選び方</h2>
<p>用途に合ったメソッドを選びます。</p>
<table>
<thead>
<tr>
<th>API</th>
<th>動作</th>
</tr>
</thead>
<tbody><tr>
<td><code>FindAsync(key)</code></td>
<td>追跡済みの主キーを先に探し、なければDBを問い合わせる</td>
</tr>
<tr>
<td><code>FirstOrDefaultAsync()</code></td>
<td>最初の1件。なければ既定値</td>
</tr>
<tr>
<td><code>SingleAsync()</code></td>
<td>必ず1件。0件・複数件なら例外</td>
</tr>
<tr>
<td><code>SingleOrDefaultAsync()</code></td>
<td>0件なら既定値、複数件なら例外</td>
</tr>
<tr>
<td><code>AnyAsync()</code></td>
<td>存在だけを確認</td>
</tr>
<tr>
<td><code>CountAsync()</code></td>
<td>件数を取得</td>
</tr>
<tr>
<td><code>ToListAsync()</code></td>
<td>結果をメモリへ実体化</td>
</tr>
</tbody></table>
<p>「最初」を決めるには <code>OrderBy</code> が必要です。<code>FindAsync</code> は追跡済みエンティティを返すことがあるため、常に最新のDB状態を取得するAPIではありません。</p>
<hr />
<h2>変更追跡・AsNoTracking</h2>
<p>操作例です。参照だけの問い合わせには <code>AsNoTracking</code> を使えます。追跡しないエンティティの変更は、そのままでは保存されません。</p>
<pre><code class="language-csharp">var detached = await db.Posts.AsNoTracking().SingleAsync();
detached.Title = "Not saved";
Console.WriteLine(db.Entry(detached).State);
Console.WriteLine(await db.SaveChangesAsync());

var tracked = await db.Posts.SingleAsync();
tracked.Title = "Saved";
tracked.Version = Guid.NewGuid();
await db.SaveChangesAsync();
</code></pre>
<p>同じコンテキストは、原則として同じ主キーのインスタンスを1つだけ追跡します。<code>AsNoTrackingWithIdentityResolution</code> は結果内の同一キーを同じインスタンスへまとめますが、コンテキストに変更を追跡させません。</p>
<hr />
<h2>関連データの読み込み</h2>
<p>操作例です。<code>Include</code> は関連エンティティを一緒に取得します。射影先に関連の値だけ必要なら、<code>Select</code> 内で参照すればよく、<code>Include</code> は不要です。</p>
<pre><code class="language-csharp">var blogs = await db.Blogs
    .AsNoTracking()
    .Include(b =&gt; b.Posts.Where(p =&gt; p.Views &gt;= 5))
    .AsSplitQuery()
    .ToListAsync();
Console.WriteLine(blogs[0].Posts.Count);

var one = await db.Blogs.SingleAsync();
await db.Entry(one).Collection(b =&gt; b.Posts).LoadAsync();
Console.WriteLine(one.Posts.Count);
</code></pre>
<p>多段の関連は <code>ThenInclude</code> を使います。<code>AsSplitQuery</code> はコレクションを別クエリで読み込み、JOINによる行数増加を抑えますが、往復回数が増え、同時更新時の一貫性にも注意が必要です。</p>
<p>追跡ありのfiltered Includeでは、以前追跡した関連エンティティがナビゲーションに混ざる場合があります。遅延読み込みは別途設定が必要で、ループ中のアクセスによるN+1クエリにも注意します。</p>
<p><a href="https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager">公式 — 関連データの一括読み込み</a></p>
<hr />
<h2>ページング</h2>
<p>操作例です。オフセット方式はページ番号に向き、キーセット方式は次ページへの移動に向きます。並び順を一意にします。</p>
<pre><code class="language-csharp">int pageSize = 20;
int pageNumber = 1;
var page = await db.Posts.AsNoTracking()
    .OrderBy(p =&gt; p.Id)
    .Skip((pageNumber - 1) * pageSize)
    .Take(pageSize)
    .ToListAsync();

int lastId = 0;
var next = await db.Posts.AsNoTracking()
    .Where(p =&gt; p.Id &gt; lastId)
    .OrderBy(p =&gt; p.Id)
    .Take(pageSize)
    .ToListAsync();
Console.WriteLine($"{page.Count}, {next.Count}");
</code></pre>
<p>実際の次ページには前ページ最後の <code>Id</code> を渡します。複数列で並べ替えるなら、カーソルの条件にも全ての並べ替え列を含めます。ページサイズは上限を設け、条件と並び順に合うインデックスを検討します。</p>
<hr />
<h2>一括更新・削除</h2>
<p>操作例です。<code>ExecuteUpdateAsync</code> / <code>ExecuteDeleteAsync</code> はEF Core 7以降のリレーショナルDB向けAPIです。エンティティを読み込まずに直接SQLを実行します。</p>
<pre><code class="language-csharp">int updated = await db.Posts.Where(p =&gt; p.Views &lt; 100)
    .ExecuteUpdateAsync(setters =&gt; setters.SetProperty(p =&gt; p.Views, p =&gt; p.Views + 1));
int deleted = await db.Posts.Where(p =&gt; p.Views == 0).ExecuteDeleteAsync();
Console.WriteLine($"{updated}, {deleted}");
</code></pre>
<p><code>SaveChanges</code> は不要です。変更トラッカーとは同期されないため、同じ行の追跡あり更新と混在させるなら再取得などが必要です。各呼び出しは別の操作で、複数の一括操作が自動的に1つのトランザクションになるわけではありません。並行性トークンも自動確認・更新されません。</p>
<p><a href="https://learn.microsoft.com/en-us/ef/core/saving/execute-insert-update-delete">公式 — ExecuteUpdate / ExecuteDelete</a></p>
<hr />
<h2>トランザクション</h2>
<p>操作例です。プロバイダーが対応していれば、1回の <code>SaveChanges</code> は既定でトランザクション内で実行されます。複数の保存や直接SQLをまとめるには明示的なトランザクションを使います。</p>
<pre><code class="language-csharp">await using var transaction = await db.Database.BeginTransactionAsync();
try
{
    db.Blogs.Add(new Blog { Name = "Transactions" });
    await db.SaveChangesAsync();
    await db.Posts.ExecuteUpdateAsync(s =&gt; s.SetProperty(p =&gt; p.Views, p =&gt; p.Views + 1));
    await transaction.CommitAsync();
}
catch
{
    await transaction.RollbackAsync();
    throw;
}
</code></pre>
<p>ロールバックしても追跡済みオブジェクトの値は元に戻りません。必要に応じてコンテキストを作り直します。再試行実行戦略を有効にしたプロバイダーでは、明示的トランザクション全体を実行戦略の単位として扱う必要があります。</p>
<hr />
<h2>楽観的同時実行制御</h2>
<p>操作例です。共通モデルの <code>Version</code> を使い、他のコンテキストによる先行更新を検出します。SQLiteにはSQL Serverの <code>rowversion</code> 相当がないため、ここではアプリがトークンを更新します。</p>
<pre><code class="language-csharp">await using var other = new BlogContext(options);
var mine = await db.Posts.SingleAsync();
var theirs = await other.Posts.SingleAsync();

theirs.Title = "Changed elsewhere";
theirs.Version = Guid.NewGuid();
await other.SaveChangesAsync();

mine.Title = "My change";
mine.Version = Guid.NewGuid();
try
{
    await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
    await db.Entry(mine).ReloadAsync();
    Console.WriteLine(mine.Title);
}
</code></pre>
<p>この例は自分の変更を破棄して再読み込みします。実際にはユーザーへの競合通知、値のマージ、条件付き再試行などを選びます。トークンは保護対象の更新経路全てで更新します。</p>
<p><a href="https://learn.microsoft.com/en-us/ef/core/saving/concurrency">公式 — 競合の処理</a></p>
<h3>SQL Server：rowversionと[Timestamp]</h3>
<p>SQL Serverの <code>rowversion</code> は、楽観ロックに使えるDB自動生成の8バイトのバイナリ値です。属性名は <code>[Timestamp]</code> ですが、<strong>日時ではありません</strong>。<code>RowVersion</code> は単なるプロパティ名で、<code>[Timestamp]</code> または <code>.IsRowVersion()</code> による設定が必要です。</p>
<p>以下はSQLiteの操作例とは別の <strong>SQL Server専用</strong> の宣言です。<code>Microsoft.EntityFrameworkCore.SqlServer</code> 10.0.12を追加し、<code>UseSqlServer(connectionString)</code> でコンテキストのオプションを作り、SQL Server向けのマイグレーションでスキーマを作成します。接続文字列は構成から取得します。</p>
<pre><code class="language-csharp">using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;

public sealed class SqlServerDocument
{
    public int Id { get; set; }
    [MaxLength(200)]
    public string Title { get; set; } = "";

    [Timestamp]
    public byte[] RowVersion { get; set; } = [];
}

public sealed class SqlServerContext(DbContextOptions&lt;SqlServerContext&gt; options)
    : DbContext(options)
{
    public DbSet&lt;SqlServerDocument&gt; Documents =&gt; Set&lt;SqlServerDocument&gt;();
}
</code></pre>
<p>SQL ServerはINSERT時と行のUPDATE時に新しい値を生成します。同じ値を設定するUPDATEでも変わります。EFは追跡ありの更新・削除で、主キーと読み込み時のトークンを条件に含めます。他の処理が行を更新・削除し、対象が0件になった場合は <code>DbUpdateConcurrencyException</code> になります。保存成功後はEFが生成値を取得するため、アプリで新しいトークンを代入しません。</p>
<table>
<thead>
<tr>
<th>指定</th>
<th>値の更新</th>
<th>主な用途</th>
</tr>
</thead>
<tbody><tr>
<td><code>[Timestamp]</code> / <code>IsRowVersion()</code></td>
<td>DBで生成</td>
<td>SQL Serverの <code>byte[]</code> / <code>rowversion</code></td>
</tr>
<tr>
<td><code>[ConcurrencyCheck]</code> / <code>IsConcurrencyToken()</code></td>
<td>この設定だけでは生成されない</td>
<td>アプリ管理の <code>Guid</code> や任意のプロパティ</td>
</tr>
</tbody></table>
<p>SQLiteに <code>[Timestamp]</code> を付けてもrowversionの自動生成機能は追加されません。前述のアプリ管理トークンを使います。<code>ExecuteUpdate</code> / <code>ExecuteDelete</code> ではEFの自動競合検出を通らないため、元のトークンを明示的に条件へ入れ、影響行数を確認します。</p>
<h3>API・編集画面から更新する場合</h3>
<p>ユーザーが編集を開始した時点のトークンを、例えばBase64としてクライアントへ返し、更新要求で受け取って <code>byte[]</code> に戻します。保存時に最新の行を読み直すだけでは、画面を開いてから保存するまでの競合を見逃します。以下のヘルパーは、上記SQL Serverの宣言と同じプロジェクトの別ファイルに置きます。</p>
<pre><code class="language-csharp">using Microsoft.EntityFrameworkCore;

public static class DocumentUpdates
{
    public static async Task&lt;byte[]&gt; UpdateTitleAsync(
        SqlServerContext db, int id, string title, byte[] originalRowVersion,
        CancellationToken cancellationToken = default)
    {
        var document = await db.Documents.SingleAsync(d =&gt; d.Id == id, cancellationToken);
        db.Entry(document).Property(d =&gt; d.RowVersion).OriginalValue = originalRowVersion;
        document.Title = title;
        await db.SaveChangesAsync(cancellationToken);
        return document.RowVersion;
    }
}
</code></pre>
<p>保存後の新しいトークンを戻します。呼び出し側で入力検証・認可を行い、対象行がない場合と競合を区別し、<code>DbUpdateConcurrencyException</code> はHTTP 409や再読み込みの案内などで扱います。変更が検出されない場合、<code>SaveChanges</code> はUPDATEを送らず、競合チェックも行いません。競合後はコンテキストの状態を解決または破棄し、そのまま無条件に再試行しません。</p>
<p><a href="https://learn.microsoft.com/en-us/ef/core/saving/concurrency">EF Coreの競合処理</a> / <a href="https://learn.microsoft.com/en-us/sql/t-sql/data-types/rowversion-transact-sql">SQL Serverのrowversion</a></p>
<hr />
<h2>ソフトデリート・クエリフィルター</h2>
<p>操作例です。共通モデルの名前付きフィルターにより、<code>IsDeleted</code> がtrueの投稿は通常の問い合わせから除外されます。</p>
<pre><code class="language-csharp">var post = await db.Posts.SingleAsync();
post.IsDeleted = true;
post.Version = Guid.NewGuid();
await db.SaveChangesAsync();
Console.WriteLine(await db.Posts.CountAsync());
var all = await db.Posts.IgnoreQueryFilters(["SoftDelete"]).ToListAsync();
Console.WriteLine(all.Count);
</code></pre>
<p>フィルターは <code>Remove</code> をソフトデリートへ変換しません。削除フラグを設定する処理が必要です。引数なしの <code>IgnoreQueryFilters()</code> は全フィルターを無効にします。フィルターだけを認可境界にせず、必要な認可を行います。</p>
<p><a href="https://learn.microsoft.com/en-us/ef/core/querying/filters">公式 — グローバルクエリフィルター</a></p>
<hr />
<h2>SQLを直接使う</h2>
<p>操作例です。<code>FromSql</code> には補間文字列を直接渡すと、値がパラメーターとして渡されます。</p>
<pre><code class="language-csharp">string title = "Hello EF Core";
var posts = await db.Posts
    .FromSql($"SELECT * FROM Posts WHERE Title = {title}")
    .AsNoTracking()
    .ToListAsync();
Console.WriteLine(posts.Count);
</code></pre>
<p>外部入力を文字列連結して <code>FromSqlRaw</code> に渡しません。列名などの識別子はパラメーター化できないため、動的にするなら許可リストで選びます。エンティティを返すSQLには、その型にマッピングされた列が必要です。</p>
<p><a href="https://learn.microsoft.com/en-us/ef/core/querying/sql-queries">公式 — SQLクエリ</a></p>
<hr />
<h2>マイグレーション</h2>
<p>以降は、別のファイルDB <code>blog.db</code> を使う手順です。<code>BlogContextFactory.cs</code> を追加します。設計時ファクトリーにより、ツールが学習用 <code>Program.cs</code> を実行せずにコンテキストを作れます。</p>
<pre><code class="language-csharp">using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;

public sealed class BlogContextFactory : IDesignTimeDbContextFactory&lt;BlogContext&gt;
{
    public BlogContext CreateDbContext(string[] args)
    {
        var options = new DbContextOptionsBuilder&lt;BlogContext&gt;()
            .UseSqlite("Data Source=blog.db")
            .Options;
        return new BlogContext(options);
    }
}
</code></pre>
<p>実際のアプリが <code>blog.db</code> を使う場合は、実行時にも同じDBを指定します。上記の学習用 <code>Program.cs</code> は引き続きインメモリDBを使います。接続先に認証情報が必要なら、ソースへ埋め込まず構成やシークレット管理から取得します。</p>
<h3>作成・適用・SQL確認</h3>
<p>プロジェクトディレクトリで実行します。<code>database update</code> は上記ファクトリーの学習用DBを変更します。</p>
<pre><code class="language-bash">dotnet ef migrations add InitialCreate --context BlogContext
dotnet ef migrations list --context BlogContext
dotnet ef migrations script 0 InitialCreate --output migration.sql --context BlogContext
dotnet ef database update --context BlogContext
dotnet ef migrations has-pending-model-changes --context BlogContext
</code></pre>
<p>モデルを変更したら、変更内容を表す名前で次のマイグレーションを追加します。生成されたコードとSQLを確認してから適用します。未適用の最後のマイグレーションを取り消すには <code>dotnet ef migrations remove --context BlogContext</code> を使います。適用済みのものをファイルだけ削除しません。</p>
<p>本番ではレビュー済みSQLやmigration bundleなどをデプロイ工程で適用します。SQLiteは冪等スクリプト <code>--idempotent</code> に対応しません。SQLiteでは上記のように開始・終了マイグレーションを指定します。</p>
<p><a href="https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/applying">公式 — マイグレーションの適用</a> / <a href="https://learn.microsoft.com/en-us/ef/core/providers/sqlite/limitations">SQLiteの制約</a></p>
<hr />
<h2>既存DBからモデル生成</h2>
<p>マイグレーションで作成済みの <code>blog.db</code> から、別の出力ディレクトリへモデルを生成する例です。</p>
<pre><code class="language-bash">dotnet ef dbcontext scaffold "Data Source=blog.db" Microsoft.EntityFrameworkCore.Sqlite --output-dir Scaffolded --context ReverseContext --no-onconfiguring
</code></pre>
<p>生成コードは確認してから使います。DBから復元できるのはスキーマ由来の情報で、クエリフィルターやアプリ管理の並行性トークンなどの意図は復元されません。<code>--no-onconfiguring</code> を使った場合は、実行時に接続設定を渡します。</p>
<hr />
<h2>DbContextの寿命・非同期処理</h2>
<p><code>DbContext</code> は短い作業単位に使い、使い終わったら破棄します。同じインスタンスを複数スレッドや未完了の非同期処理で共有しません。</p>
<ul>
<li><a href="http://ASP.NET">ASP.NET</a> Coreの <code>AddDbContext</code> は既定でscoped登録です。通常はリクエスト単位で使います。</li>
<li>バックグラウンド処理など、DIスコープと作業単位が一致しない場合は <code>IDbContextFactory&lt;T&gt;</code> を検討します。作成したコンテキストは呼び出し側で破棄します。</li>
<li>同じコンテキストへのクエリを <code>Task.WhenAll</code> で同時実行しません。並列処理には別コンテキストを用意します。</li>
<li><code>ToListAsync(cancellationToken)</code> / <code>SaveChangesAsync(cancellationToken)</code> へキャンセルトークンを渡せます。キャンセルの対応はプロバイダーにも依存します。</li>
<li>SQLiteの非同期APIは基盤の制約により同期的に実行されるため、この例だけで他DBの非同期性能を判断しません。</li>
</ul>
<p><a href="https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/">公式 — DbContextの構成と寿命</a> / <a href="https://learn.microsoft.com/en-us/dotnet/standard/data/sqlite/async">SQLiteの非同期制約</a></p>
<hr />
<h2>SQL確認・性能のチェック</h2>
<p>操作例です。<code>ToQueryString</code> はSQLの確認用で、クエリを実行しません。実際の実行SQLや時間はログ・DB側の実行計画も確認します。</p>
<pre><code class="language-csharp">var query = db.Posts
    .TagWith("Posts list")
    .AsNoTracking()
    .Where(p =&gt; p.BlogId == blog.Id)
    .OrderBy(p =&gt; p.Id)
    .Take(20);
Console.WriteLine(query.ToQueryString());
</code></pre>
<ul>
<li>必要な列だけ射影し、全件取得を避けます。</li>
<li>N+1、不要な <code>Include</code>、巨大なJOIN、オフセットの大きいページングを確認します。</li>
<li><code>EnableSensitiveDataLogging</code> は値をログへ含めます。常時有効にせず、必要な開発環境に限定します。</li>
<li>実行計画を見てインデックスを判断します。EFのAPI名だけで性能を決めません。</li>
</ul>
<hr />
<h2>テスト</h2>
<p>操作例です。保存後に別コンテキストで読み直し、追跡済みオブジェクトだけを検証しないようにします。</p>
<pre><code class="language-csharp">db.Posts.Add(new Post { BlogId = blog.Id, Title = "Persistence test" });
await db.SaveChangesAsync();
await using var verification = new BlogContext(options);
var saved = await verification.Posts.AsNoTracking()
    .SingleAsync(p =&gt; p.Title == "Persistence test");
if (saved.Id &lt;= 0 || saved.BlogId != blog.Id)
    throw new InvalidOperationException("Persistence check failed.");
Console.WriteLine("Persistence check passed.");
</code></pre>
<p>これは例外で失敗を示す最小の実行確認です。テストプロジェクトではMSTestなどのAssertへ置き換えます。</p>
<p>SQLiteのインメモリDBはリレーショナルな制約やSQLの一部を試せますが、本番のSQL ServerやPostgreSQLの代替にはなりません。重要なクエリ、照合順序、トランザクション、マイグレーションは本番と同じDBエンジンでも検証します。EF Core InMemoryプロバイダーはリレーショナルDBの動作を再現しません。</p>
<p><a href="https://learn.microsoft.com/en-us/ef/core/testing/choosing-a-testing-strategy">公式 — テスト戦略</a></p>
<hr />
<h2>バージョン・プロバイダーごとの注意点</h2>
<p>このページの例はEF Core 10のSQLiteプロバイダーを前提にしています。</p>
<table>
<thead>
<tr>
<th>機能・用途</th>
<th>注意点</th>
</tr>
</thead>
<tbody><tr>
<td>一括更新・削除</td>
<td><code>ExecuteUpdate</code> / <code>ExecuteDelete</code> はEF Core 7以降</td>
</tr>
<tr>
<td>名前付きクエリフィルター</td>
<td>EF Core 10以降。旧版では1つの式に <code>&amp;&amp;</code> でまとめる</td>
</tr>
<tr>
<td>SQL Serverの並行性制御</td>
<td>DB生成の <code>rowversion</code> を利用可能。SQLiteでは同じ指定を流用しない</td>
</tr>
<tr>
<td>文字列長・数値精度</td>
<td>DBによって制約・型・変換可能な操作が異なる</td>
</tr>
<tr>
<td>SQLiteのスキーマ変更</td>
<td>一部の操作はテーブル再構築が必要。スキーマ・シーケンスは非対応</td>
</tr>
<tr>
<td>DBプロバイダー</td>
<td>SQL Serverは <code>UseSqlServer</code>、SQLiteは <code>UseSqlite</code>、Npgsqlは <code>UseNpgsql</code>。別パッケージが必要</td>
</tr>
</tbody></table>
<p>メジャー更新時は破壊的変更とプロバイダーの対応状況を確認します。このページの例だけで他プロバイダーのSQL変換や挙動まで保証するものではありません。</p>
<p><a href="https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-10.0/whatsnew">EF Core 10の新機能</a> / <a href="https://learn.microsoft.com/en-us/ef/core/providers/">プロバイダー一覧</a></p>
<hr />
<h2>関連資料</h2>
<p><a href="https://learn.microsoft.com/en-us/ef/core/">EF Core公式ドキュメント</a></p>
]]></content:encoded></item><item><title><![CDATA[C# チートシート]]></title><description><![CDATA[C# 14・.NET 10の基本構文をコード例で確認できるチートシート。型とnull、コレクション、LINQ、async/await、パターンマッチング、テストまで、開発で使う書き方をまとめています。]]></description><link>https://nobuo-miura.hashnode.dev/c-sharp-cheat-sheet-ja</link><guid isPermaLink="true">https://nobuo-miura.hashnode.dev/c-sharp-cheat-sheet-ja</guid><category><![CDATA[C#]]></category><category><![CDATA[cheatsheet]]></category><dc:creator><![CDATA[Nobuo Miura]]></dc:creator><pubDate>Thu, 26 Nov 2026 11:55:11 GMT</pubDate><content:encoded><![CDATA[<p>C# 14・.NET 10をベースにしたチートシートです。日常的に使う構文と標準ライブラリを、説明とサンプルでまとめています。</p>
<hr />
<h2>C#バージョンごとの比較</h2>
<p>このページの基準となる安定版C# 14までの主要な追加機能をまとめます。機能の登場時期を示す表で、各実行環境のサポート期間を示すものではありません。プレビュー機能は含めていません。</p>
<table>
<thead>
<tr>
<th>C#</th>
<th>公開年</th>
<th>主な追加機能</th>
</tr>
</thead>
<tbody><tr>
<td>1.0 / 1.2</td>
<td>2002 / 2003</td>
<td>クラス、構造体、インターフェース、デリゲート／1.2で細部の改善</td>
</tr>
<tr>
<td>2.0</td>
<td>2005</td>
<td>ジェネリクス、Nullable値型、イテレーター、匿名メソッド</td>
</tr>
<tr>
<td>3.0</td>
<td>2007</td>
<td>LINQ、ラムダ、拡張メソッド、<code>var</code>、匿名型</td>
</tr>
<tr>
<td>4.0</td>
<td>2010</td>
<td><code>dynamic</code>、名前付き・省略可能引数、ジェネリクスの共変性・反変性</td>
</tr>
<tr>
<td>5.0</td>
<td>2012</td>
<td><code>async</code> / <code>await</code>、呼び出し元情報</td>
</tr>
<tr>
<td>6.0</td>
<td>2015</td>
<td>文字列補間、<code>?.</code>、<code>nameof</code>、式形式のメンバー</td>
</tr>
<tr>
<td>7.0</td>
<td>2017</td>
<td>タプル・分解、パターンマッチング、ローカル関数、<code>out var</code></td>
</tr>
<tr>
<td>7.1</td>
<td>2017</td>
<td><code>async Main</code>、<code>default</code> リテラル</td>
</tr>
<tr>
<td>7.2</td>
<td>2017</td>
<td><code>readonly struct</code>、<code>ref struct</code>、<code>in</code> 引数</td>
</tr>
<tr>
<td>7.3</td>
<td>2018</td>
<td><code>unmanaged</code> / <code>Enum</code> / <code>Delegate</code> 制約</td>
</tr>
<tr>
<td>8.0</td>
<td>2019</td>
<td>Nullable参照型、switch式、非同期ストリーム、範囲、using宣言</td>
</tr>
<tr>
<td>9.0</td>
<td>2020</td>
<td>record、<code>init</code>、トップレベルステートメント、ターゲット型の <code>new</code></td>
</tr>
<tr>
<td>10</td>
<td>2021</td>
<td><code>record struct</code>、<code>global using</code>、ファイルスコープ名前空間</td>
</tr>
<tr>
<td>11</td>
<td>2022</td>
<td>raw文字列、<code>required</code>、リストパターン、ジェネリック数学</td>
</tr>
<tr>
<td>12</td>
<td>2023</td>
<td>コレクション式、クラス・構造体のプライマリコンストラクター</td>
</tr>
<tr>
<td>13</td>
<td>2024</td>
<td><code>params</code> コレクション、<code>System.Threading.Lock</code> 対応、ref structの制約緩和</td>
</tr>
<tr>
<td>14</td>
<td>2025</td>
<td>拡張メンバー、<code>field</code>、null条件付き代入</td>
</tr>
</tbody></table>
<p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-version-history">公式 — C#のバージョン履歴</a> / <a href="https://github.com/dotnet/csharplang/blob/main/Language-Version-History.md">機能別の履歴</a></p>
<h3>ターゲットフレームワークと既定の言語バージョン</h3>
<p>現在のSDKで <code>LangVersion</code> を上書きしない場合、ターゲットフレームワークから言語バージョンが選ばれます。これは古いC#が最初に公開されたときの環境とは別の対応表です。</p>
<table>
<thead>
<tr>
<th>ターゲット</th>
<th>既定のC#</th>
</tr>
</thead>
<tbody><tr>
<td>.NET 10</td>
<td>14</td>
</tr>
<tr>
<td>.NET 9</td>
<td>13</td>
</tr>
<tr>
<td>.NET 8</td>
<td>12</td>
</tr>
<tr>
<td>.NET 7</td>
<td>11</td>
</tr>
<tr>
<td>.NET 6</td>
<td>10</td>
</tr>
<tr>
<td>.NET 5</td>
<td>9.0</td>
</tr>
<tr>
<td>.NET Core 3.x / .NET Standard 2.1</td>
<td>8.0</td>
</tr>
<tr>
<td>.NET Core 2.x / .NET Standard 2.0 / .NET Framework</td>
<td>7.3</td>
</tr>
</tbody></table>
<p>通常はターゲットフレームワークの既定値を使います。<code>LangVersion</code> を <code>latest</code> にするとインストール済みコンパイラーに結果が依存し、不足するランタイムAPIが追加されるわけではありません。<code>global.json</code> はSDK、<code>TargetFramework</code> は対象環境、<code>LangVersion</code> は受け付ける構文を指定します。対象環境の対応表を超える言語バージョンの使用はサポートされません。</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-versioning">公式 — 言語バージョンの選択</a></p>
<h3>Visual Studioとのバージョン対応</h3>
<p>各安定版C#が導入されたWindows版Visual Studioのバージョンをまとめます。導入時の対応表であり、現在サポート中のIDE一覧ではありません。Visual Studio Codeは別製品です。</p>
<table>
<thead>
<tr>
<th>C#</th>
<th>導入時のVisual Studio</th>
</tr>
</thead>
<tbody><tr>
<td>1.0</td>
<td>Visual Studio .NET 2002</td>
</tr>
<tr>
<td>1.2</td>
<td>Visual Studio .NET 2003</td>
</tr>
<tr>
<td>2.0</td>
<td>Visual Studio 2005</td>
</tr>
<tr>
<td>3.0</td>
<td>Visual Studio 2008</td>
</tr>
<tr>
<td>4.0</td>
<td>Visual Studio 2010</td>
</tr>
<tr>
<td>5.0</td>
<td>Visual Studio 2012</td>
</tr>
<tr>
<td>6.0</td>
<td>Visual Studio 2015</td>
</tr>
<tr>
<td>7.0</td>
<td>Visual Studio 2017 (15.0)</td>
</tr>
<tr>
<td>7.1</td>
<td>Visual Studio 2017 (15.3)</td>
</tr>
<tr>
<td>7.2</td>
<td>Visual Studio 2017 (15.5)</td>
</tr>
<tr>
<td>7.3</td>
<td>Visual Studio 2017 (15.7)</td>
</tr>
<tr>
<td>8.0</td>
<td>Visual Studio 2019 (16.3)</td>
</tr>
<tr>
<td>9.0</td>
<td>Visual Studio 2019 (16.8)</td>
</tr>
<tr>
<td>10</td>
<td>Visual Studio 2022 (17.0)</td>
</tr>
<tr>
<td>11</td>
<td>Visual Studio 2022 (17.4)</td>
</tr>
<tr>
<td>12</td>
<td>Visual Studio 2022 (17.8)</td>
</tr>
<tr>
<td>13</td>
<td>Visual Studio 2022 (17.12)</td>
</tr>
<tr>
<td>14</td>
<td>Visual Studio 2026 (18.0)</td>
</tr>
</tbody></table>
<p>新しいコンパイラーでも古いC#構文は扱えますが、古いプロジェクトを開いてビルドできるかは、プロジェクト形式・ターゲットフレームワーク・インストール済みワークロードにも依存します。製品名の年とバージョン番号は別で、Visual Studio 2022は17.x系、Visual Studio 2026は18.x系です。</p>
<p><a href="https://github.com/dotnet/csharplang/blob/main/Language-Version-History.md">公式 — C#とVisual Studioの履歴</a></p>
<h4>近年の.NETをVisual Studioでターゲットにする条件</h4>
<table>
<thead>
<tr>
<th>ターゲット</th>
<th>既定のC#</th>
<th>ターゲット指定に必要なVisual Studio</th>
</tr>
</thead>
<tbody><tr>
<td>.NET 8</td>
<td>12</td>
<td>Visual Studio 2022 (17.8) 以降</td>
</tr>
<tr>
<td>.NET 9</td>
<td>13</td>
<td>Visual Studio 2022 (17.12) 以降</td>
</tr>
<tr>
<td>.NET 10</td>
<td>14</td>
<td>Visual Studio 2026 (18.0) 以降</td>
</tr>
</tbody></table>
<p>古いVisual StudioからSDKを使用できることと、そのSDKの最新ランタイムをターゲットにできることは別です。<a href="http://xn--r8j3dr99h.NET">例えば.NET</a> 10 SDK 10.0.100はVisual Studio 2022 17.14でも使用できますが、Visual Studio内で <code>net10.0</code> をターゲットにするには2026 18.0以降が必要です。<code>global.json</code> で選択するSDKのフィーチャーバンドと、IDEが対応するSDKも確認します。Visual Studio外の <code>dotnet build</code> では、インストール済みSDKとプロジェクト設定がビルド環境を決めます。</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/core/porting/versioning-sdk-msbuild-vs">公式 — SDK・MSBuild・Visual Studioの互換性</a></p>
<h3>よく使う書き方の変化</h3>
<table>
<thead>
<tr>
<th>用途</th>
<th>従来の書き方</th>
<th>新しい書き方</th>
<th>導入版</th>
</tr>
</thead>
<tbody><tr>
<td>文字列補間</td>
<td><code>"Hello, " + name</code></td>
<td><code>$"Hello, {name}"</code></td>
<td>6</td>
</tr>
<tr>
<td>null時の代替値を代入</td>
<td><code>if (name == null) name = "guest";</code></td>
<td><code>name ??= "guest";</code></td>
<td>8</td>
</tr>
<tr>
<td>オブジェクト生成</td>
<td><code>List&lt;int&gt; values = new List&lt;int&gt;();</code></td>
<td><code>List&lt;int&gt; values = new();</code></td>
<td>9</td>
</tr>
<tr>
<td>配列の初期化</td>
<td><code>int[] values = new[] { 1, 2 };</code></td>
<td><code>int[] values = [1, 2];</code></td>
<td>12</td>
</tr>
<tr>
<td>nullでなければ代入</td>
<td><code>if (person is not null) person.Name = "Ada";</code></td>
<td><code>person?.Name = "Ada";</code></td>
<td>14</td>
</tr>
</tbody></table>
<p>従来の書き方も引き続き使えます。新構文は重複を減らせますが、一般に高速化を意味するわけではありません。本文のraw文字列・<code>required</code> はC# 11、コレクション式はC# 12、<code>System.Threading.Lock</code> の例はC# <a href="http://xn--13-jb4a.NET">13と.NET</a> 9以降を使います。</p>
<hr />
<h2>インストール・プロジェクト作成</h2>
<p><a href="https://dotnet.microsoft.com/en-us/download/dotnet/10.0">.NET公式ダウンロード</a>から、<a href="http://xn--OS-r93apa3by023b.NET">OSに合った.NET</a> 10 SDKをインストールします。Runtimeだけではビルドできません。既存プロジェクトでは <code>global.json</code> のSDK指定と <code>.csproj</code> のターゲットフレームワークを優先します。</p>
<pre><code class="language-bash">dotnet --version
dotnet --list-sdks
dotnet new console -n HelloCSharp --framework net10.0
cd HelloCSharp
dotnet run
dotnet build -c Release
</code></pre>
<hr />
<h2>基本構造</h2>
<p>以下の例は、コンソールプロジェクトの <code>Program.cs</code> に記述します。トップレベルステートメントを使うと、<code>Main</code> メソッドの宣言を省略できます。</p>
<pre><code class="language-csharp">// 標準出力へ表示
Console.WriteLine("Hello, C#!");
Console.WriteLine($"Arguments: {args.Length}");
</code></pre>
<p>このページのC#コードブロックは、特記しない限り、それぞれ独立して <code>Program.cs</code> に置き換えて試せます。<code>net10.0</code>、<code>ImplicitUsings</code> と <code>Nullable</code> が <code>enable</code> のコンソールプロジェクトを想定しています。型宣言はトップレベルステートメントの後に置きます。</p>
<hr />
<h2>コメント</h2>
<p><code>//</code> は行コメント、<code>/* ... */</code> はブロックコメント、<code>///</code> はXMLドキュメントコメントです。</p>
<pre><code class="language-csharp">Console.WriteLine(MathHelpers.Add(2, 3));

public static class MathHelpers
{
    /// &lt;summary&gt;2つの整数を加算します。&lt;/summary&gt;
    public static int Add(int left, int right) =&gt; left + right;
}
</code></pre>
<hr />
<h2>変数・定数・基本型</h2>
<p><code>var</code> は初期値から型を推論します。動的型ではなく、宣言時に型が決まります。ローカル変数は使用前に代入が必要です。</p>
<pre><code class="language-csharp">int count = 3;
long population = 8_000_000_000L;
double ratio = 0.5;
decimal price = 1_980.50m;
bool enabled = true;
char initial = 'C';
string language = "C#";
var names = new List&lt;string&gt;();
const int MaxRetries = 3;
Console.WriteLine($"{count}, {population}, {ratio}, {price}, {enabled}, {initial}, {language}, {names.Count}, {MaxRetries}");
</code></pre>
<table>
<thead>
<tr>
<th>型</th>
<th>用途・注意点</th>
</tr>
</thead>
<tbody><tr>
<td><code>byte</code> / <code>sbyte</code></td>
<td>8ビット符号なし／符号付き整数</td>
</tr>
<tr>
<td><code>short</code> / <code>ushort</code></td>
<td>16ビット整数</td>
</tr>
<tr>
<td><code>int</code> / <code>uint</code></td>
<td>32ビット整数</td>
</tr>
<tr>
<td><code>long</code> / <code>ulong</code></td>
<td>64ビット整数</td>
</tr>
<tr>
<td><code>nint</code> / <code>nuint</code></td>
<td>プラットフォーム依存サイズの整数</td>
</tr>
<tr>
<td><code>float</code> / <code>double</code></td>
<td>2進浮動小数点。<code>float</code> リテラルには <code>f</code></td>
</tr>
<tr>
<td><code>decimal</code></td>
<td>10進数の計算。リテラルには <code>m</code>。丸めや範囲の制約はある</td>
</tr>
<tr>
<td><code>bool</code></td>
<td><code>true</code> / <code>false</code></td>
</tr>
<tr>
<td><code>char</code></td>
<td>UTF-16コード単位1つ。常に1文字とは限らない</td>
</tr>
<tr>
<td><code>string</code></td>
<td>不変のUTF-16文字列</td>
</tr>
<tr>
<td><code>object</code></td>
<td>全ての型の共通の基底型。値型の代入はボックス化を伴う</td>
</tr>
</tbody></table>
<p>フィールドや配列要素は既定値（数値は <code>0</code>、<code>bool</code> は <code>false</code>、参照型は <code>null</code>）で初期化されます。<code>readonly</code> フィールドは宣言時またはコンストラクターで代入でき、コンパイル時定数の <code>const</code> とは異なります。</p>
<hr />
<h2>型変換・数値演算</h2>
<p>整数同士の除算は整数になります。外部入力の変換には、失敗を戻り値で扱える <code>TryParse</code> が便利です。</p>
<pre><code class="language-csharp">Console.WriteLine(5 / 2);       // 2
Console.WriteLine(5 / 2.0);     // 2.5
if (int.TryParse("42", out int value))
    Console.WriteLine(value);

double source = 3.9;
int truncated = (int)source;
Console.WriteLine(truncated);
try
{
    int max = int.MaxValue;
    Console.WriteLine(checked(max + 1));
}
catch (OverflowException)
{
    Console.WriteLine("Overflow");
}
</code></pre>
<p><code>checked</code> は整数演算・変換のオーバーフロー検出に使います。書式付きの数値や日時を保存・交換する場合は、カルチャーも明示します。</p>
<hr />
<h2>null・Nullable参照型</h2>
<p><code>int?</code> はnullを持てる値型です。<code>string?</code> はnullを許容する参照型としてコンパイラーに意図を伝えます。Nullable参照型の警告は実行時チェックを追加しません。</p>
<pre><code class="language-csharp">string? name = null;
int? length = name?.Length;
Console.WriteLine(length ?? 0);
name ??= "guest";
if (name is { Length: &gt; 0 })
    Console.WriteLine(name.ToUpperInvariant());

int? score = null;
Console.WriteLine(score.GetValueOrDefault());
</code></pre>
<p><code>?.</code> はnullの場合にアクセスを省略し、<code>??</code> は代替値、<code>??=</code> はnullの場合の代入です。<code>!</code> は警告を抑制するだけで、nullを安全にしません。</p>
<hr />
<h2>文字列</h2>
<p>文字列は不変です。補間は <code>$"..."</code>、パスなどでバックスラッシュをそのまま書くには <code>@"..."</code>、複数行のテキストにはraw文字列リテラルを使えます。</p>
<pre><code class="language-csharp">string name = "Ada";
string path = @"C:\work\notes.txt";
string json = """
    {"name":"Ada","active":true}
    """;
Console.WriteLine($"Hello, {name}! {path}");
Console.WriteLine(json);
Console.WriteLine(string.Join(" | ", " alpha,beta ".Trim().Split(',')));
Console.WriteLine(string.Join(" / ", new[] { "alpha", "beta" }));
Console.WriteLine("CSharp".Contains("sharp", StringComparison.OrdinalIgnoreCase));
Console.WriteLine(name[..2]);
</code></pre>
<p>識別子などの比較では <code>StringComparison.Ordinal</code> / <code>OrdinalIgnoreCase</code> を明示します。表示用の自然言語ではカルチャーを考慮します。大量の連結には <code>StringBuilder</code> が使えます。</p>
<hr />
<h2>制御構文・パターンマッチング</h2>
<p><code>if</code>、<code>for</code>、<code>foreach</code>、<code>while</code>、<code>do</code> を使えます。<code>switch</code> 式はパターンから値を選びます。</p>
<pre><code class="language-csharp">int score = 85;
if (score &gt;= 60)
    Console.WriteLine("Pass");

string grade = score switch
{
    &gt;= 90 =&gt; "A",
    &gt;= 80 =&gt; "B",
    &gt;= 60 =&gt; "C",
    _ =&gt; "D"
};
Console.WriteLine(grade);
for (int i = 0; i &lt; 3; i++)
    Console.WriteLine(i);
foreach (int number in new[] { 1, 2, 3 })
{
    if (number == 2) continue;
    Console.WriteLine(number);
}
int remaining = 2;
while (remaining &gt; 0) remaining--;
do { remaining++; } while (remaining &lt; 1);

object item = "hello";
if (item is string { Length: &gt; 0 } text)
    Console.WriteLine(text);
int[] values = [1, 2, 3];
Console.WriteLine(values is [1, .., 3]);
</code></pre>
<p><code>break</code> はループやswitch文を抜け、<code>continue</code> は次の反復に進みます。switch文の各節は通常 <code>break</code> や <code>return</code> で終え、暗黙に次の節へ進みません。</p>
<hr />
<h2>メソッド・引数・タプル</h2>
<p>ローカル関数も宣言できます。複数の結果にはタプル、可変長引数には <code>params</code>、名前付き引数には <code>名前: 値</code> を使います。</p>
<pre><code class="language-csharp">Console.WriteLine(Greet(name: "Ada"));
Console.WriteLine(Sum(1, 2, 3));
var (min, max) = Bounds([8, 2, 5]);
Console.WriteLine($"{min}..{max}");
int count = 1;
Increment(ref count);
Console.WriteLine(count);

static string Greet(string name, string prefix = "Hello") =&gt; $"{prefix}, {name}";
static int Sum(params int[] values) =&gt; values.Sum();
static (int Min, int Max) Bounds(int[] values) =&gt; (values.Min(), values.Max());
static void Increment(ref int value) =&gt; value++;
</code></pre>
<p><code>ref</code> は初期化済み変数を参照渡し、<code>out</code> は呼び出し先で必ず代入する出力、<code>in</code> は読み取り専用の参照渡しです。通常の引数は値渡しで、参照型の場合は参照の値がコピーされます。</p>
<hr />
<h2>配列・List・Dictionary・HashSet</h2>
<p>配列は長さが固定、<code>List&lt;T&gt;</code> は要素数を変更できる配列ベースのコレクションです。<code>Dictionary&lt;TKey, TValue&gt;</code> はキーと値、<code>HashSet&lt;T&gt;</code> は重複しない値を保持します。</p>
<pre><code class="language-csharp">int[] numbers = [10, 20, 30];
Console.WriteLine(numbers[^1]);
int[] firstTwo = numbers[..2];
List&lt;string&gt; names = ["Ada", "Linus"];
names.Add("Grace");
names.Remove("Linus");
Console.WriteLine($"{numbers.Length}, {firstTwo.Length}, {names.Count}");

var scores = new Dictionary&lt;string, int&gt;(StringComparer.OrdinalIgnoreCase)
{
    ["Ada"] = 90
};
if (scores.TryGetValue("ada", out int score))
    Console.WriteLine(score);
scores["Grace"] = 95;
foreach (var (name, points) in scores)
    Console.WriteLine($"{name}: {points}");

HashSet&lt;int&gt; unique = [1, 1, 2];
Console.WriteLine(unique.Add(2));
Console.WriteLine(unique.Contains(1));
</code></pre>
<p>配列の範囲アクセス <code>numbers[..2]</code> は新しい配列を作ります。<code>List&lt;T&gt;</code> の <code>Capacity</code> は確保済み容量、<code>Count</code> は実際の要素数です。通常のコレクションを複数スレッドから同時に変更する場合は同期が必要です。</p>
<hr />
<h2>クラス・プロパティ・アクセス修飾子</h2>
<p>クラスは参照型です。<code>required</code> は初期化時の指定を要求し、<code>init</code> は初期化時だけ設定できるプロパティを作ります。</p>
<pre><code class="language-csharp">var account = new Account("A-001") { Owner = "Ada" };
account.Deposit(100m);
Console.WriteLine($"{account.Id}: {account.Owner}, {account.Balance}");

public sealed class Account(string id)
{
    public string Id { get; } = id;
    public required string Owner { get; init; }
    public decimal Balance { get; private set; }

    public void Deposit(decimal amount)
    {
        if (amount &lt;= 0) throw new ArgumentOutOfRangeException(nameof(amount));
        Balance += amount;
    }
}
</code></pre>
<table>
<thead>
<tr>
<th>修飾子</th>
<th>アクセス範囲</th>
</tr>
</thead>
<tbody><tr>
<td><code>public</code></td>
<td>制限なし（包含する型の範囲内）</td>
</tr>
<tr>
<td><code>private</code></td>
<td>宣言した型の内部</td>
</tr>
<tr>
<td><code>protected</code></td>
<td>宣言した型と派生型</td>
</tr>
<tr>
<td><code>internal</code></td>
<td>同一アセンブリ</td>
</tr>
<tr>
<td><code>protected internal</code></td>
<td>同一アセンブリ、または派生型</td>
</tr>
<tr>
<td><code>private protected</code></td>
<td>同一アセンブリ内の派生型と宣言した型</td>
</tr>
</tbody></table>
<p><code>sealed</code> は継承を禁止します。プライマリコンストラクターの引数は、通常のクラスでは自動的に公開プロパティになりません。<code>required</code> は値の妥当性を保証しません。</p>
<hr />
<h2>構造体・record・等値性</h2>
<p><code>struct</code> は値型で、代入すると値がコピーされます。<code>record</code> は値に基づく等値比較を生成します。既定の <code>record</code> は参照型、<code>record struct</code> は値型です。</p>
<pre><code class="language-csharp">var original = new Person("Ada", 36);
var updated = original with { Age = 37 };
Console.WriteLine(original == new Person("Ada", 36));
Console.WriteLine(updated);
var point = new Point(1, 2);
var copy = point with { X = 5 };
Console.WriteLine($"{point} / {copy}");

public record Person(string Name, int Age);
public readonly record struct Point(int X, int Y);
</code></pre>
<p><code>with</code> は浅いコピーです。参照型のメンバーは共有されるため、recordでも深い不変性は保証されません。値型にも参照型のフィールドを含められ、その参照はコピー先と共有されます。</p>
<hr />
<h2>継承・インターフェース</h2>
<p>クラスが継承できる基底クラスは1つですが、インターフェースは複数実装できます。共通の契約をインターフェースで表現します。</p>
<pre><code class="language-csharp">IShape shape = new Circle(3);
Console.WriteLine(shape.Area);
Animal animal = new Dog();
animal.Speak();

public interface IShape
{
    double Area { get; }
}
public sealed class Circle(double radius) : IShape
{
    public double Area =&gt; Math.PI * radius * radius;
}
public abstract class Animal
{
    public abstract void Speak();
}
public sealed class Dog : Animal
{
    public override void Speak() =&gt; Console.WriteLine("Woof");
}
</code></pre>
<p>基底クラスで実装付きの上書き可能なメソッドを定義するには <code>virtual</code>、派生クラスで上書きするには <code>override</code> を使います。<code>new</code> によるメンバーの隠蔽とは異なります。</p>
<hr />
<h2>enum・フラグ</h2>
<p>列挙型は名前付きの整数値を表します。フラグでは各ビットに値を割り当てます。</p>
<pre><code class="language-csharp">Access access = Access.Read | Access.Write;
Console.WriteLine(access.HasFlag(Access.Read));
Console.WriteLine((access &amp; Access.Write) != 0);
Console.WriteLine(Enum.IsDefined(Status.Ready));

public enum Status { Unknown, Ready, Done }
[Flags]
public enum Access { None = 0, Read = 1, Write = 2, Execute = 4 }
</code></pre>
<p>整数からキャストすれば未定義の値も作れます。外部入力では妥当性を確認します。フラグの組み合わせは <code>Enum.IsDefined</code> では個別定義がないと認められません。</p>
<hr />
<h2>ジェネリクス</h2>
<p>型パラメーターを使うと、型安全性を保ったまま処理やデータ構造を共通化できます。<code>where</code> は使用可能な型を制約します。</p>
<pre><code class="language-csharp">Console.WriteLine(Max(3, 7));
var box = new Box&lt;string&gt;("hello");
Console.WriteLine(box.Value);

static T Max&lt;T&gt;(T left, T right) where T : IComparable&lt;T&gt;
    =&gt; left.CompareTo(right) &gt;= 0 ? left : right;

public sealed class Box&lt;T&gt;(T value)
{
    public T Value { get; } = value;
}
</code></pre>
<p>代表的な制約は <code>class</code>、<code>struct</code>、<code>notnull</code>、インターフェース、<code>new()</code> です。<code>new()</code> はpublicの引数なしコンストラクターを要求し、他の通常の制約より後に書きます。</p>
<hr />
<h2>ラムダ・デリゲート・イベント</h2>
<p><code>Func&lt;...&gt;</code> は戻り値あり、<code>Action&lt;...&gt;</code> は戻り値なしの処理を保持します。ラムダは外側の変数をキャプチャできます。イベントは発行元から購読者へ通知します。</p>
<pre><code class="language-csharp">int factor = 2;
Func&lt;int, int&gt; multiply = value =&gt; value * factor;
factor = 3;
Console.WriteLine(multiply(4));
Action&lt;string&gt; print = message =&gt; Console.WriteLine(message);
print("Ready");

var counter = new Counter();
EventHandler handler = (_, _) =&gt; Console.WriteLine("Changed");
counter.Changed += handler;
counter.Increment();
counter.Changed -= handler;

public sealed class Counter
{
    public int Value { get; private set; }
    public event EventHandler? Changed;
    public void Increment()
    {
        Value++;
        Changed?.Invoke(this, EventArgs.Empty);
    }
}
</code></pre>
<p>キャプチャされるのは変数であり、その時点の値のスナップショットではありません。長寿命の発行元へのイベント購読は、不要になったら解除します。キャプチャ不要のラムダには <code>static</code> を付けられます。</p>
<hr />
<h2>LINQ</h2>
<p>LINQはコレクションなどに対して、抽出・変換・集約を記述する仕組みです。メソッド構文とクエリ構文があります。</p>
<pre><code class="language-csharp">int[] numbers = [1, 2, 3, 4, 5];
var query = numbers.Where(n =&gt; n % 2 == 0).Select(n =&gt; n * 10);
int[] result = query.ToArray();
Console.WriteLine(string.Join(", ", result));
Console.WriteLine(numbers.Any(n =&gt; n &gt; 4));
Console.WriteLine(numbers.All(n =&gt; n &gt; 0));
Console.WriteLine(numbers.Sum());
Console.WriteLine(numbers.FirstOrDefault(n =&gt; n &gt; 10, -1));

var descending = from n in numbers
                 where n &gt;= 3
                 orderby n descending
                 select n;
Console.WriteLine(string.Join(", ", descending));
foreach (var group in numbers.GroupBy(n =&gt; n % 2))
    Console.WriteLine($"{group.Key}: {group.Count()}");
</code></pre>
<table>
<thead>
<tr>
<th>操作</th>
<th>主なメソッド</th>
</tr>
</thead>
<tbody><tr>
<td>抽出・射影</td>
<td><code>Where</code>, <code>Select</code>, <code>SelectMany</code></td>
</tr>
<tr>
<td>並べ替え</td>
<td><code>OrderBy</code>, <code>OrderByDescending</code>, <code>ThenBy</code></td>
</tr>
<tr>
<td>先頭・末尾・単一</td>
<td><code>First</code>, <code>Last</code>, <code>Single</code> と各 <code>OrDefault</code></td>
</tr>
<tr>
<td>件数制限</td>
<td><code>Take</code>, <code>Skip</code>, <code>TakeWhile</code></td>
</tr>
<tr>
<td>集約</td>
<td><code>Count</code>, <code>Sum</code>, <code>Average</code>, <code>Min</code>, <code>Max</code>, <code>Aggregate</code></td>
</tr>
<tr>
<td>集合</td>
<td><code>Distinct</code>, <code>Union</code>, <code>Intersect</code>, <code>Except</code></td>
</tr>
<tr>
<td>実体化</td>
<td><code>ToArray</code>, <code>ToList</code>, <code>ToDictionary</code></td>
</tr>
</tbody></table>
<p><code>Where</code> や <code>Select</code> は通常、列挙時に実行されます（遅延実行）。複数回列挙すると処理も再実行されるため、結果を固定したい場合は実体化します。<code>SingleOrDefault</code> も複数件なら例外になります。<code>ToDictionary</code> はキー重複で例外になります。<code>IQueryable&lt;T&gt;</code> はプロバイダーによってSQLなどに変換され、通常のメモリ上のLINQと実行条件が異なります。</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/linq/get-started/introduction-to-linq-queries">公式ガイド — LINQクエリ</a></p>
<hr />
<h2>イテレーター・yield</h2>
<p><code>yield return</code> で要素を順に返すイテレーターを定義できます。全件を先に配列へ格納する必要はありません。</p>
<pre><code class="language-csharp">foreach (int value in CountUp(3))
    Console.WriteLine(value);

static IEnumerable&lt;int&gt; CountUp(int count)
{
    for (int i = 0; i &lt; count; i++)
        yield return i;
}
</code></pre>
<p>イテレーター本体の処理や例外は通常、メソッドの呼び出し時ではなく列挙時に発生します。<code>yield break</code> で列挙を終了できます。</p>
<hr />
<h2>例外処理</h2>
<p>回復できる例外を具体的な型で捕捉します。リソース解放には <code>finally</code> や <code>using</code> を使います。</p>
<pre><code class="language-csharp">try
{
    Console.WriteLine(ParsePositive("-1"));
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine(ex.ParamName);
}
catch (FormatException)
{
    Console.WriteLine("Invalid number");
}
finally
{
    Console.WriteLine("Finished");
}

static int ParsePositive(string text)
{
    int value = int.Parse(text);
    if (value &lt;= 0)
        throw new ArgumentOutOfRangeException(nameof(text), "Must be positive.");
    return value;
}
</code></pre>
<p>再スローは <code>throw;</code> を使い、元のスタックトレースを保ちます。<code>throw ex;</code> はスタックトレースをリセットします。想定内の入力エラーでは、例外を通常の分岐として使うより <code>TryParse</code> などを検討します。</p>
<hr />
<h2>using・リソース管理</h2>
<p>GCはメモリを管理しますが、ファイルや接続などのリソースは適切なタイミングで解放する必要があります。<code>using</code> は <code>IDisposable.Dispose</code> をスコープ終了時に呼び出します。</p>
<pre><code class="language-csharp">using var stream = new MemoryStream();
using (var writer = new StreamWriter(stream, leaveOpen: true))
{
    writer.Write("hello");
}
stream.Position = 0;
using var reader = new StreamReader(stream);
Console.WriteLine(reader.ReadToEnd());
</code></pre>
<p>非同期解放の <code>IAsyncDisposable</code> には <code>await using</code> を使います。<code>using</code> ディレクティブ（名前空間のインポート）とは別の用途です。</p>
<hr />
<h2>async・await・キャンセル</h2>
<p>非同期メソッドは一般に <code>Task</code> / <code>Task&lt;T&gt;</code> を返します。<code>await</code> は未完了の処理を待つ間、呼び出し元へ制御を返せます。<code>async</code> 自体は別スレッドを起動しません。</p>
<pre><code class="language-csharp">using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2));
try
{
    Task&lt;int&gt; first = WorkAsync(1, cts.Token);
    Task&lt;int&gt; second = WorkAsync(2, cts.Token);
    int[] results = await Task.WhenAll(first, second);
    Console.WriteLine(string.Join(", ", results));
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
    Console.WriteLine("Canceled");
}

static async Task&lt;int&gt; WorkAsync(int value, CancellationToken cancellationToken)
{
    await Task.Delay(20, cancellationToken);
    return value * 2;
}
</code></pre>
<p>キャンセルは協調的です。トークンを下位APIに渡し、CPU処理では必要に応じて <code>ThrowIfCancellationRequested()</code> を呼びます。<code>Task.WhenAll</code> はすべてのタスクの完了を待ち、1つの失敗で他のタスクを自動キャンセルしません。</p>
<p><code>.Result</code> や <code>.Wait()</code> による同期的な待機は避け、呼び出し元まで <code>await</code> を伝播します。<code>async void</code> は通常イベントハンドラーに限定します。I/Oには非同期APIを使い、CPU負荷の高い処理を別スレッドで行いたい場合に <code>Task.Run</code> を検討します。</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/">公式ガイド — 非同期プログラミング</a></p>
<hr />
<h2>非同期ストリーム</h2>
<p><code>IAsyncEnumerable&lt;T&gt;</code> は要素を非同期で順番に取得するための型です。<code>await foreach</code> で列挙します。</p>
<pre><code class="language-csharp">using System.Runtime.CompilerServices;

using var cts = new CancellationTokenSource();
await foreach (int value in ReadAsync(cts.Token))
    Console.WriteLine(value);

static async IAsyncEnumerable&lt;int&gt; ReadAsync(
    [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
    for (int i = 0; i &lt; 3; i++)
    {
        await Task.Delay(10, cancellationToken);
        yield return i;
    }
}
</code></pre>
<hr />
<h2>並行処理・同期</h2>
<p>共有状態の更新は同期します。単純なカウンターには <code>Interlocked</code>、複数の操作をまとめて保護する場合は <code>lock</code> が使えます。</p>
<pre><code class="language-csharp">int count = 0;
Parallel.For(0, 1_000, _ =&gt; Interlocked.Increment(ref count));
Console.WriteLine(count);

var gate = new System.Threading.Lock();
List&lt;int&gt; values = [];
Parallel.For(0, 10, i =&gt;
{
    lock (gate)
    {
        values.Add(i);
    }
});
Console.WriteLine(values.Count);
</code></pre>
<p><code>lock</code> 内で <code>await</code> は使えません。非同期処理の同時実行数制限には <code>SemaphoreSlim.WaitAsync</code> と <code>finally</code> での <code>Release</code> を使います。<code>ConcurrentDictionary</code> なども、複数操作全体の原子性まで自動的に保証するわけではありません。</p>
<hr />
<h2>Span・Memory</h2>
<p><code>Span&lt;T&gt;</code> は連続したメモリへのビューで、スライス時に要素をコピーしません。<code>ReadOnlySpan&lt;T&gt;</code> はビューを通じた書き込みを禁止します。</p>
<pre><code class="language-csharp">int[] values = [1, 2, 3, 4];
Span&lt;int&gt; middle = values.AsSpan(1, 2);
middle[0] = 20;
Console.WriteLine(values[1]);
ReadOnlySpan&lt;char&gt; prefix = "hello".AsSpan(0, 2);
Console.WriteLine(prefix.ToString());
</code></pre>
<p><code>Span&lt;T&gt;</code> は <code>ref struct</code> で、通常のクラスのフィールドに保持できず、<code>await</code> をまたいで使用できません。そのような寿命が必要なら <code>Memory&lt;T&gt;</code> を検討します。読み取り専用ビューでも、元の配列が他から変更される可能性はあります。</p>
<hr />
<h2>標準ライブラリ早引き</h2>
<p>よく使う型と名前空間をまとめます。</p>
<table>
<thead>
<tr>
<th>用途</th>
<th>型・名前空間</th>
</tr>
</thead>
<tbody><tr>
<td>文字列の構築</td>
<td><code>System.Text.StringBuilder</code></td>
</tr>
<tr>
<td>正規表現</td>
<td><code>System.Text.RegularExpressions.Regex</code></td>
</tr>
<tr>
<td>日時・期間</td>
<td><code>DateTimeOffset</code>, <code>DateOnly</code>, <code>TimeOnly</code>, <code>TimeSpan</code></td>
</tr>
<tr>
<td>ファイル・パス</td>
<td><code>System.IO.File</code>, <code>Directory</code>, <code>Path</code></td>
</tr>
<tr>
<td>JSON</td>
<td><code>System.Text.Json.JsonSerializer</code></td>
</tr>
<tr>
<td>HTTP</td>
<td><code>System.Net.Http.HttpClient</code></td>
</tr>
<tr>
<td>UUID</td>
<td><code>Guid</code></td>
</tr>
<tr>
<td>非暗号用途の乱数</td>
<td><code>Random.Shared</code></td>
</tr>
<tr>
<td>暗号用途の乱数</td>
<td><code>System.Security.Cryptography.RandomNumberGenerator</code></td>
</tr>
<tr>
<td>並行コレクション</td>
<td><code>System.Collections.Concurrent</code></td>
</tr>
<tr>
<td>非同期キュー</td>
<td><code>System.Threading.Channels</code></td>
</tr>
<tr>
<td>処理時間の測定</td>
<td><code>System.Diagnostics.Stopwatch</code></td>
</tr>
</tbody></table>
<h3>日時・期間</h3>
<p>保存・通信する時刻にはUTCやオフセットを明示し、表示時に必要なタイムゾーンへ変換します。</p>
<pre><code class="language-csharp">using System.Globalization;

DateTimeOffset now = DateTimeOffset.UtcNow;
string encoded = now.ToString("O", CultureInfo.InvariantCulture);
DateTimeOffset restored = DateTimeOffset.Parse(encoded, CultureInfo.InvariantCulture);
DateOnly date = new(2026, 9, 14);
TimeOnly time = new(9, 30);
TimeSpan duration = TimeSpan.FromMinutes(45);
Console.WriteLine($"{restored:O}, {date:yyyy-MM-dd}, {time:HH:mm}, {duration}");
</code></pre>
<p><code>DateTimeOffset</code> が保持するのはオフセットで、タイムゾーンの規則ではありません。夏時間などの変換には <code>TimeZoneInfo</code> を使います。</p>
<h3>ファイル・パス</h3>
<p>次の例は一時ファイルを作成し、読み書きした後に削除します。</p>
<pre><code class="language-csharp">string path = Path.GetTempFileName();
try
{
    await File.WriteAllTextAsync(path, "hello");
    string text = await File.ReadAllTextAsync(path);
    Console.WriteLine(text);
    Console.WriteLine(Path.GetFileName(path));
}
finally
{
    File.Delete(path);
}
</code></pre>
<p>大きなファイルはストリームや <code>File.ReadLines</code> で逐次処理します。<code>Path.Combine</code> はパス結合のAPIで、外部入力を指定ディレクトリ内に制限する検証ではありません。</p>
<h3>JSON</h3>
<p>標準の <code>System.Text.Json</code> でシリアライズ・デシリアライズできます。</p>
<pre><code class="language-csharp">using System.Text.Json;

var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
var person = new Person("Ada", 36);
string json = JsonSerializer.Serialize(person, options);
Console.WriteLine(json);
Person restored = JsonSerializer.Deserialize&lt;Person&gt;(json, options)
    ?? throw new JsonException("Expected a person.");
Console.WriteLine(restored.Name);

public record Person(string Name, int Age);
</code></pre>
<p>通常の既定設定ではプロパティ名の照合は大文字小文字を区別します。Web用の既定設定とは異なります。デシリアライズ後は業務上必要な値の検証も行います。</p>
<h3>HTTP</h3>
<p>次はネットワーク接続が必要な例です。<code>HttpClient</code> はアプリケーションの寿命に合わせて再利用するか、DI環境では <code>IHttpClientFactory</code> で管理します。</p>
<pre><code class="language-csharp">using System.Net;

using var handler = new SocketsHttpHandler
{
    PooledConnectionLifetime = TimeSpan.FromMinutes(2),
    AutomaticDecompression = DecompressionMethods.All
};
using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(10) };
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
using var response = await client.GetAsync("https://example.com/", cts.Token);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync(cts.Token));
</code></pre>
<p>このコンソール例では終了時に破棄します。長時間動くアプリでリクエストごとに生成・破棄する使い方は避けます。実際のアプリではHTTPエラー、接続失敗、タイムアウト・キャンセルを要件に合わせて処理します。</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient-guidelines">公式ガイド — HttpClientの利用指針</a></p>
<hr />
<h2>名前空間・プロジェクト・NuGet</h2>
<p>名前空間は型の名前を整理します。以下はクラスライブラリ内のファイル例で、<code>Program.cs</code> の実行例ではありません。</p>
<pre><code class="language-csharp">namespace Sample.Library;

public static class Calculator
{
    public static int Add(int left, int right) =&gt; left + right;
}
</code></pre>
<p>ファイルスコープ名前空間は、そのファイル全体に適用されます。<code>using Sample.Library;</code> で型名を短く書けますが、別プロジェクトの利用にはプロジェクト参照も必要です。</p>
<h3>CLIコマンド</h3>
<p>以下はチートシート用の独立したソリューションを作る手順です。<code>dotnet new sln</code> <a href="http://xn--v9j.NET">は.NET</a> 10では既定で <code>.slnx</code> を作成します。</p>
<pre><code class="language-bash">dotnet new sln -n CheatSheet
dotnet new classlib -n Sample.Library --framework net10.0
dotnet new console -n Sample.App --framework net10.0
dotnet sln CheatSheet.slnx add Sample.Library/Sample.Library.csproj Sample.App/Sample.App.csproj
dotnet reference add Sample.Library/Sample.Library.csproj --project Sample.App/Sample.App.csproj
dotnet restore CheatSheet.slnx
dotnet build CheatSheet.slnx
dotnet format CheatSheet.slnx --verify-no-changes
dotnet publish Sample.App/Sample.App.csproj -c Release
</code></pre>
<p>NuGetパッケージは <code>dotnet package add パッケージ名 --project プロジェクトパス</code> で追加します。採用前に公式NuGetページで安定版・対応フレームワークを確認し、更新は <code>dotnet package list --outdated</code> で確認します。再現性が必要ならパッケージバージョンやSDKを固定します。</p>
<hr />
<h2>テスト</h2>
<p>前節のソリューションにMSTestプロジェクトを追加します。テンプレートがテスト用パッケージを設定します。ここでは<a href="https://www.nuget.org/packages/MSTest/4.4.0">MSTest 4.4.0</a>を明示します。</p>
<pre><code class="language-bash">dotnet new mstest -n Sample.Tests --framework net10.0
dotnet package add MSTest --version 4.4.0 --project Sample.Tests/Sample.Tests.csproj
dotnet sln CheatSheet.slnx add Sample.Tests/Sample.Tests.csproj
dotnet reference add Sample.Library/Sample.Library.csproj --project Sample.Tests/Sample.Tests.csproj
dotnet test CheatSheet.slnx
</code></pre>
<h3>テストコード</h3>
<p><code>Sample.Library</code> のクラスライブラリに前節の <code>Calculator</code> を配置し、テストプロジェクトの生成されたテストファイルを次のコードで置き換えます。</p>
<pre><code class="language-csharp">using Microsoft.VisualStudio.TestTools.UnitTesting;
using Sample.Library;

namespace Sample.Tests;

[TestClass]
public sealed class CalculatorTests
{
    [TestMethod]
    [DataRow(2, 3, 5)]
    [DataRow(-2, 2, 0)]
    [DataRow(0, 0, 0)]
    public void Add_ReturnsSum(int left, int right, int expected)
    {
        Assert.AreEqual(expected, Calculator.Add(left, right));
    }
}
</code></pre>
<p>このブロックはMSTestプロジェクト用で、単独のコンソールでは実行できません。変更後にもう一度 <code>dotnet test CheatSheet.slnx</code> を実行します。非同期テストは <code>async Task</code> を返し、処理を <code>await</code> します。</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-csharp-with-mstest">公式ガイド — C#とMSTest</a></p>
<hr />
<h2>C# 14の構文</h2>
<p>C# 14では拡張メンバー、<code>field</code> を使うプロパティ、null条件付き代入などが追加されました。以下は代表的な例です。</p>
<pre><code class="language-csharp">Console.WriteLine("hello".IsLong);
var person = new Person();
person.Name = " Ada ";
Console.WriteLine(person.Name);
Person? missing = null;
missing?.Name = "Grace";
Console.WriteLine(nameof(List&lt;&gt;));

public static class TextExtensions
{
    extension(string text)
    {
        public bool IsLong =&gt; text.Length &gt;= 5;
    }
}
public sealed class Person
{
    public string Name
    {
        get;
        set =&gt; field = value.Trim();
    } = "";
}
</code></pre>
<p>null条件付き代入は対象がnullなら右辺も評価しません。<code>field</code> はコンパイラー生成のバッキングフィールドを表します。既存の拡張メソッド構文 <code>this</code> も引き続き使用できます。</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-14">公式リファレンス — C# 14の新機能</a></p>
<hr />
<h2>Tips・よくあるミス</h2>
<ul>
<li>整数除算で小数が消える：演算前に少なくとも一方を浮動小数点型や <code>decimal</code> にします。</li>
<li><code>==</code> の意味を混同する：通常のクラスは既定で参照比較、recordは値比較、文字列は内容比較です。配列の要素比較には <code>SequenceEqual</code> を使います。</li>
<li>Nullableの <code>!</code> に頼る：実行時のnullチェックではありません。入力を検証します。</li>
<li>LINQを何度も列挙する：遅延実行に注意し、必要なら <code>ToList</code> などで結果を保持します。</li>
<li><code>foreach</code> 中に元の <code>List&lt;T&gt;</code> を変更する：<code>RemoveAll</code> や別コレクションへの投影などを使います。</li>
<li>非同期処理を待ち忘れる：戻されたタスクを <code>await</code> し、例外と完了を観測します。</li>
<li><code>async</code> を並列化と考える：非同期I/OとCPUの並列処理を分けて考えます。</li>
<li><code>Random</code> をシークレット生成に使う：暗号用途には <code>RandomNumberGenerator</code> を使います。</li>
<li><code>DateTime.Now</code> をタイムゾーン不明のまま保存する：UTCやオフセットを明示します。</li>
<li>recordや <code>readonly</code> を深い不変性と考える：参照先のオブジェクトまで不変にはなりません。</li>
</ul>
<hr />
<h2>公式リファレンス</h2>
<ul>
<li><a href="https://learn.microsoft.com/en-us/dotnet/csharp/">C#ドキュメント</a></li>
<li><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/">言語リファレンス</a></li>
<li><a href="https://learn.microsoft.com/en-us/dotnet/api/">.NET APIブラウザー</a></li>
<li><a href="https://learn.microsoft.com/en-us/dotnet/core/tools/">.NET CLI</a></li>
<li><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version">C#言語バージョンの設定</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[C# Cheat Sheet]]></title><description><![CDATA[A practical C# 14 and .NET 10 cheat sheet with code examples for syntax, nullable types, collections, LINQ, async/await, pattern matching, and testing]]></description><link>https://nobuo-miura.hashnode.dev/c-cheat-sheet</link><guid isPermaLink="true">https://nobuo-miura.hashnode.dev/c-cheat-sheet</guid><category><![CDATA[C#]]></category><category><![CDATA[cheatsheet]]></category><dc:creator><![CDATA[Nobuo Miura]]></dc:creator><pubDate>Thu, 26 Nov 2026 11:47:11 GMT</pubDate><content:encoded><![CDATA[<p>This cheat sheet is based on C# 14 and .NET 10. It covers everyday language features and standard library APIs with examples.</p>
<hr />
<h2>C# version comparison</h2>
<p>The table lists selected additions through C# 14, the stable baseline used here. It is a feature history, not a support-lifecycle table. Preview features are excluded.</p>
<table>
<thead>
<tr>
<th>C#</th>
<th>Released</th>
<th>Main additions</th>
</tr>
</thead>
<tbody><tr>
<td>1.0 / 1.2</td>
<td>2002 / 2003</td>
<td>Classes, structs, interfaces, delegates; refinements in 1.2</td>
</tr>
<tr>
<td>2.0</td>
<td>2005</td>
<td>Generics, nullable value types, iterators, anonymous methods</td>
</tr>
<tr>
<td>3.0</td>
<td>2007</td>
<td>LINQ, lambdas, extension methods, <code>var</code>, anonymous types</td>
</tr>
<tr>
<td>4.0</td>
<td>2010</td>
<td><code>dynamic</code>, named and optional arguments, generic covariance and contravariance</td>
</tr>
<tr>
<td>5.0</td>
<td>2012</td>
<td><code>async</code> / <code>await</code>, caller information</td>
</tr>
<tr>
<td>6.0</td>
<td>2015</td>
<td>String interpolation, <code>?.</code>, <code>nameof</code>, expression-bodied members</td>
</tr>
<tr>
<td>7.0</td>
<td>2017</td>
<td>Tuples and deconstruction, pattern matching, local functions, <code>out var</code></td>
</tr>
<tr>
<td>7.1</td>
<td>2017</td>
<td><code>async Main</code>, default literals</td>
</tr>
<tr>
<td>7.2</td>
<td>2017</td>
<td><code>readonly struct</code>, <code>ref struct</code>, <code>in</code> parameters</td>
</tr>
<tr>
<td>7.3</td>
<td>2018</td>
<td><code>unmanaged</code>, <code>Enum</code>, and <code>Delegate</code> constraints</td>
</tr>
<tr>
<td>8.0</td>
<td>2019</td>
<td>Nullable reference types, switch expressions, async streams, ranges, using declarations</td>
</tr>
<tr>
<td>9.0</td>
<td>2020</td>
<td>Records, <code>init</code>, top-level statements, target-typed <code>new</code></td>
</tr>
<tr>
<td>10</td>
<td>2021</td>
<td><code>record struct</code>, <code>global using</code>, file-scoped namespaces</td>
</tr>
<tr>
<td>11</td>
<td>2022</td>
<td>Raw strings, <code>required</code>, list patterns, generic math</td>
</tr>
<tr>
<td>12</td>
<td>2023</td>
<td>Collection expressions, primary constructors for classes and structs</td>
</tr>
<tr>
<td>13</td>
<td>2024</td>
<td><code>params</code> collections, <code>System.Threading.Lock</code> support, relaxed ref struct restrictions</td>
</tr>
<tr>
<td>14</td>
<td>2025</td>
<td>Extension members, <code>field</code>, null-conditional assignment</td>
</tr>
</tbody></table>
<p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-version-history">Official C# version history</a> / <a href="https://github.com/dotnet/csharplang/blob/main/Language-Version-History.md">Feature-by-feature history</a></p>
<h3>Target framework and default language version</h3>
<p>With a current SDK and no <code>LangVersion</code> override, the compiler selects a language version from the target framework. This mapping is separate from the original release environment of older C# versions.</p>
<table>
<thead>
<tr>
<th>Target</th>
<th>Default C#</th>
</tr>
</thead>
<tbody><tr>
<td>.NET 10</td>
<td>14</td>
</tr>
<tr>
<td>.NET 9</td>
<td>13</td>
</tr>
<tr>
<td>.NET 8</td>
<td>12</td>
</tr>
<tr>
<td>.NET 7</td>
<td>11</td>
</tr>
<tr>
<td>.NET 6</td>
<td>10</td>
</tr>
<tr>
<td>.NET 5</td>
<td>9.0</td>
</tr>
<tr>
<td>.NET Core 3.x / .NET Standard 2.1</td>
<td>8.0</td>
</tr>
<tr>
<td>.NET Core 2.x / .NET Standard 2.0 / .NET Framework</td>
<td>7.3</td>
</tr>
</tbody></table>
<p>Prefer the target framework’s default. Setting <code>LangVersion</code> to <code>latest</code> makes the result depend on the installed compiler and does not supply missing runtime APIs. <code>global.json</code> selects the SDK; <code>TargetFramework</code> selects the target; <code>LangVersion</code> controls accepted syntax. Using a newer language version than the target’s supported mapping is unsupported.</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-versioning">Official language versioning</a></p>
<h3>Visual Studio version mapping</h3>
<p>The table shows the Windows Visual Studio release that introduced each stable C# version. It is a historical introduction map, not a list of currently supported IDE releases. Visual Studio Code is a separate product.</p>
<table>
<thead>
<tr>
<th>C#</th>
<th>Visual Studio at introduction</th>
</tr>
</thead>
<tbody><tr>
<td>1.0</td>
<td>Visual Studio .NET 2002</td>
</tr>
<tr>
<td>1.2</td>
<td>Visual Studio .NET 2003</td>
</tr>
<tr>
<td>2.0</td>
<td>Visual Studio 2005</td>
</tr>
<tr>
<td>3.0</td>
<td>Visual Studio 2008</td>
</tr>
<tr>
<td>4.0</td>
<td>Visual Studio 2010</td>
</tr>
<tr>
<td>5.0</td>
<td>Visual Studio 2012</td>
</tr>
<tr>
<td>6.0</td>
<td>Visual Studio 2015</td>
</tr>
<tr>
<td>7.0</td>
<td>Visual Studio 2017 (15.0)</td>
</tr>
<tr>
<td>7.1</td>
<td>Visual Studio 2017 (15.3)</td>
</tr>
<tr>
<td>7.2</td>
<td>Visual Studio 2017 (15.5)</td>
</tr>
<tr>
<td>7.3</td>
<td>Visual Studio 2017 (15.7)</td>
</tr>
<tr>
<td>8.0</td>
<td>Visual Studio 2019 (16.3)</td>
</tr>
<tr>
<td>9.0</td>
<td>Visual Studio 2019 (16.8)</td>
</tr>
<tr>
<td>10</td>
<td>Visual Studio 2022 (17.0)</td>
</tr>
<tr>
<td>11</td>
<td>Visual Studio 2022 (17.4)</td>
</tr>
<tr>
<td>12</td>
<td>Visual Studio 2022 (17.8)</td>
</tr>
<tr>
<td>13</td>
<td>Visual Studio 2022 (17.12)</td>
</tr>
<tr>
<td>14</td>
<td>Visual Studio 2026 (18.0)</td>
</tr>
</tbody></table>
<p>Later compiler versions also understand older C# syntax, but opening and building an old project still depends on its project type, target framework, and installed workloads. The year in a product name and its version number differ: Visual Studio 2022 is the 17.x family; Visual Studio 2026 is the 18.x family.</p>
<p><a href="https://github.com/dotnet/csharplang/blob/main/Language-Version-History.md">Official C# / Visual Studio history</a></p>
<h4>Targeting recent .NET versions in Visual Studio</h4>
<table>
<thead>
<tr>
<th>Target</th>
<th>Default C#</th>
<th>Minimum Visual Studio for targeting</th>
</tr>
</thead>
<tbody><tr>
<td>.NET 8</td>
<td>12</td>
<td>Visual Studio 2022 (17.8) or later</td>
</tr>
<tr>
<td>.NET 9</td>
<td>13</td>
<td>Visual Studio 2022 (17.12) or later</td>
</tr>
<tr>
<td>.NET 10</td>
<td>14</td>
<td>Visual Studio 2026 (18.0) or later</td>
</tr>
</tbody></table>
<p>An SDK being usable by an older Visual Studio does not mean that IDE supports targeting the SDK’s newest runtime. For example, .NET 10 SDK 10.0.100 can work with Visual Studio 2022 17.14, but targeting <code>net10.0</code> in Visual Studio requires 2026 18.0 or later. Also check the SDK feature band selected by <code>global.json</code> against the IDE’s supported SDKs. With <code>dotnet build</code> outside Visual Studio, the installed SDK and project settings determine the build environment.</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/core/porting/versioning-sdk-msbuild-vs">Official SDK / MSBuild / Visual Studio compatibility</a></p>
<h3>How common syntax changed</h3>
<table>
<thead>
<tr>
<th>Task</th>
<th>Earlier form</th>
<th>Newer form</th>
<th>Introduced</th>
</tr>
</thead>
<tbody><tr>
<td>Interpolation</td>
<td><code>"Hello, " + name</code></td>
<td><code>$"Hello, {name}"</code></td>
<td>6</td>
</tr>
<tr>
<td>Assign a null fallback</td>
<td><code>if (name == null) name = "guest";</code></td>
<td><code>name ??= "guest";</code></td>
<td>8</td>
</tr>
<tr>
<td>Construct an object</td>
<td><code>List&lt;int&gt; values = new List&lt;int&gt;();</code></td>
<td><code>List&lt;int&gt; values = new();</code></td>
<td>9</td>
</tr>
<tr>
<td>Initialize an array</td>
<td><code>int[] values = new[] { 1, 2 };</code></td>
<td><code>int[] values = [1, 2];</code></td>
<td>12</td>
</tr>
<tr>
<td>Assign through a non-null receiver</td>
<td><code>if (person is not null) person.Name = "Ada";</code></td>
<td><code>person?.Name = "Ada";</code></td>
<td>14</td>
</tr>
</tbody></table>
<p>Older forms remain valid. The newer syntax may reduce repetition; it does not generally imply faster execution. In the snippets below, raw strings and <code>required</code> need C# 11, collection expressions need C# 12, and the <code>System.Threading.Lock</code> example uses C# 13 with .NET 9 or later.</p>
<hr />
<h2>Installation and project setup</h2>
<p>Install the .NET 10 SDK for your OS from the <a href="https://dotnet.microsoft.com/en-us/download/dotnet/10.0">official .NET download page</a>. The runtime alone cannot build applications. For an existing project, follow the SDK selection in <code>global.json</code> and the target framework in its <code>.csproj</code> file.</p>
<pre><code class="language-bash">dotnet --version
dotnet --list-sdks
dotnet new console -n HelloCSharp --framework net10.0
cd HelloCSharp
dotnet run
dotnet build -c Release
</code></pre>
<hr />
<h2>Program structure</h2>
<p>Write this example in the console project’s <code>Program.cs</code>. Top-level statements let you omit an explicit <code>Main</code> method.</p>
<pre><code class="language-csharp">// Write to standard output.
Console.WriteLine("Hello, C#!");
Console.WriteLine($"Arguments: {args.Length}");
</code></pre>
<p>Unless stated otherwise, each C# block on this page can replace <code>Program.cs</code> independently. Examples assume a <code>net10.0</code> console project with <code>ImplicitUsings</code> and <code>Nullable</code> enabled. Type declarations follow top-level statements.</p>
<hr />
<h2>Comments</h2>
<p>Use <code>//</code> for line comments, <code>/* ... */</code> for block comments, and <code>///</code> for XML documentation comments.</p>
<pre><code class="language-csharp">Console.WriteLine(MathHelpers.Add(2, 3));

public static class MathHelpers
{
    /// &lt;summary&gt;Adds two integers.&lt;/summary&gt;
    public static int Add(int left, int right) =&gt; left + right;
}
</code></pre>
<hr />
<h2>Variables, constants, and built-in types</h2>
<p><code>var</code> infers a static type from the initializer; it does not make a variable dynamically typed. Local variables must be assigned before use.</p>
<pre><code class="language-csharp">int count = 3;
long population = 8_000_000_000L;
double ratio = 0.5;
decimal price = 1_980.50m;
bool enabled = true;
char initial = 'C';
string language = "C#";
var names = new List&lt;string&gt;();
const int MaxRetries = 3;
Console.WriteLine($"{count}, {population}, {ratio}, {price}, {enabled}, {initial}, {language}, {names.Count}, {MaxRetries}");
</code></pre>
<table>
<thead>
<tr>
<th>Type</th>
<th>Purpose and notes</th>
</tr>
</thead>
<tbody><tr>
<td><code>byte</code> / <code>sbyte</code></td>
<td>Unsigned / signed 8-bit integers</td>
</tr>
<tr>
<td><code>short</code> / <code>ushort</code></td>
<td>16-bit integers</td>
</tr>
<tr>
<td><code>int</code> / <code>uint</code></td>
<td>32-bit integers</td>
</tr>
<tr>
<td><code>long</code> / <code>ulong</code></td>
<td>64-bit integers</td>
</tr>
<tr>
<td><code>nint</code> / <code>nuint</code></td>
<td>Platform-sized integers</td>
</tr>
<tr>
<td><code>float</code> / <code>double</code></td>
<td>Binary floating point; use <code>f</code> for <code>float</code> literals</td>
</tr>
<tr>
<td><code>decimal</code></td>
<td>Decimal arithmetic; use <code>m</code> for literals. Precision and range are still limited</td>
</tr>
<tr>
<td><code>bool</code></td>
<td><code>true</code> / <code>false</code></td>
</tr>
<tr>
<td><code>char</code></td>
<td>One UTF-16 code unit, not necessarily a complete character</td>
</tr>
<tr>
<td><code>string</code></td>
<td>An immutable UTF-16 string</td>
</tr>
<tr>
<td><code>object</code></td>
<td>The common base type; assigning a value type involves boxing</td>
</tr>
</tbody></table>
<p>Fields and array elements receive default values: <code>0</code> for numbers, <code>false</code> for <code>bool</code>, and <code>null</code> for reference types. A <code>readonly</code> field can be assigned at its declaration or in a constructor, unlike a compile-time <code>const</code>.</p>
<hr />
<h2>Conversions and numeric operations</h2>
<p>Integer division produces an integer. <code>TryParse</code> reports conversion failure through its return value, making it useful for external input.</p>
<pre><code class="language-csharp">Console.WriteLine(5 / 2);       // 2
Console.WriteLine(5 / 2.0);     // 2.5
if (int.TryParse("42", out int value))
    Console.WriteLine(value);

double source = 3.9;
int truncated = (int)source;
Console.WriteLine(truncated);
try
{
    int max = int.MaxValue;
    Console.WriteLine(checked(max + 1));
}
catch (OverflowException)
{
    Console.WriteLine("Overflow");
}
</code></pre>
<p>Use <code>checked</code> to detect overflow in integer arithmetic and conversions. Specify a culture when persisting or exchanging formatted numbers and dates.</p>
<hr />
<h2>Null and nullable reference types</h2>
<p><code>int?</code> is a nullable value type. <code>string?</code> tells the compiler that a reference may be null. Nullable reference type warnings do not add runtime checks.</p>
<pre><code class="language-csharp">string? name = null;
int? length = name?.Length;
Console.WriteLine(length ?? 0);
name ??= "guest";
if (name is { Length: &gt; 0 })
    Console.WriteLine(name.ToUpperInvariant());

int? score = null;
Console.WriteLine(score.GetValueOrDefault());
</code></pre>
<p><code>?.</code> skips access on null, <code>??</code> supplies a fallback, and <code>??=</code> assigns only on null. The null-forgiving operator <code>!</code> only suppresses warnings; it does not make a value safe.</p>
<hr />
<h2>Strings</h2>
<p>Strings are immutable. Use <code>$"..."</code> for interpolation, <code>@"..."</code> to preserve backslashes in paths, and raw string literals for multiline text.</p>
<pre><code class="language-csharp">string name = "Ada";
string path = @"C:\work\notes.txt";
string json = """
    {"name":"Ada","active":true}
    """;
Console.WriteLine($"Hello, {name}! {path}");
Console.WriteLine(json);
Console.WriteLine(string.Join(" | ", " alpha,beta ".Trim().Split(',')));
Console.WriteLine(string.Join(" / ", new[] { "alpha", "beta" }));
Console.WriteLine("CSharp".Contains("sharp", StringComparison.OrdinalIgnoreCase));
Console.WriteLine(name[..2]);
</code></pre>
<p>Specify <code>StringComparison.Ordinal</code> or <code>OrdinalIgnoreCase</code> for identifier-like comparisons. Consider culture for human-language text. <code>StringBuilder</code> is useful for repeated concatenation.</p>
<hr />
<h2>Control flow and pattern matching</h2>
<p>Use <code>if</code>, <code>for</code>, <code>foreach</code>, <code>while</code>, and <code>do</code> for control flow. A <code>switch</code> expression selects a value using patterns.</p>
<pre><code class="language-csharp">int score = 85;
if (score &gt;= 60)
    Console.WriteLine("Pass");

string grade = score switch
{
    &gt;= 90 =&gt; "A",
    &gt;= 80 =&gt; "B",
    &gt;= 60 =&gt; "C",
    _ =&gt; "D"
};
Console.WriteLine(grade);
for (int i = 0; i &lt; 3; i++)
    Console.WriteLine(i);
foreach (int number in new[] { 1, 2, 3 })
{
    if (number == 2) continue;
    Console.WriteLine(number);
}
int remaining = 2;
while (remaining &gt; 0) remaining--;
do { remaining++; } while (remaining &lt; 1);

object item = "hello";
if (item is string { Length: &gt; 0 } text)
    Console.WriteLine(text);
int[] values = [1, 2, 3];
Console.WriteLine(values is [1, .., 3]);
</code></pre>
<p><code>break</code> exits a loop or switch statement; <code>continue</code> advances to the next iteration. Switch statement sections normally end with <code>break</code> or <code>return</code> and do not implicitly fall through.</p>
<hr />
<h2>Methods, parameters, and tuples</h2>
<p>You can declare local functions. Use tuples for multiple results, <code>params</code> for a variable number of arguments, and <code>name: value</code> for named arguments.</p>
<pre><code class="language-csharp">Console.WriteLine(Greet(name: "Ada"));
Console.WriteLine(Sum(1, 2, 3));
var (min, max) = Bounds([8, 2, 5]);
Console.WriteLine($"{min}..{max}");
int count = 1;
Increment(ref count);
Console.WriteLine(count);

static string Greet(string name, string prefix = "Hello") =&gt; $"{prefix}, {name}";
static int Sum(params int[] values) =&gt; values.Sum();
static (int Min, int Max) Bounds(int[] values) =&gt; (values.Min(), values.Max());
static void Increment(ref int value) =&gt; value++;
</code></pre>
<p><code>ref</code> passes an initialized variable by reference, <code>out</code> requires assignment by the callee, and <code>in</code> passes a readonly reference. Ordinary arguments pass by value; for reference types, that value is a reference.</p>
<hr />
<h2>Arrays, List, Dictionary, and HashSet</h2>
<p>Arrays have a fixed length. <code>List&lt;T&gt;</code> is an array-backed collection that can grow. <code>Dictionary&lt;TKey, TValue&gt;</code> stores key-value pairs, while <code>HashSet&lt;T&gt;</code> stores unique values.</p>
<pre><code class="language-csharp">int[] numbers = [10, 20, 30];
Console.WriteLine(numbers[^1]);
int[] firstTwo = numbers[..2];
List&lt;string&gt; names = ["Ada", "Linus"];
names.Add("Grace");
names.Remove("Linus");
Console.WriteLine($"{numbers.Length}, {firstTwo.Length}, {names.Count}");

var scores = new Dictionary&lt;string, int&gt;(StringComparer.OrdinalIgnoreCase)
{
    ["Ada"] = 90
};
if (scores.TryGetValue("ada", out int score))
    Console.WriteLine(score);
scores["Grace"] = 95;
foreach (var (name, points) in scores)
    Console.WriteLine($"{name}: {points}");

HashSet&lt;int&gt; unique = [1, 1, 2];
Console.WriteLine(unique.Add(2));
Console.WriteLine(unique.Contains(1));
</code></pre>
<p>An array range such as <code>numbers[..2]</code> creates a new array. A list’s <code>Capacity</code> is its allocated capacity; <code>Count</code> is its actual element count. Ordinary collections require synchronization for concurrent mutation.</p>
<hr />
<h2>Classes, properties, and accessibility</h2>
<p>Classes are reference types. <code>required</code> requires initialization, and <code>init</code> limits property assignment to initialization.</p>
<pre><code class="language-csharp">var account = new Account("A-001") { Owner = "Ada" };
account.Deposit(100m);
Console.WriteLine($"{account.Id}: {account.Owner}, {account.Balance}");

public sealed class Account(string id)
{
    public string Id { get; } = id;
    public required string Owner { get; init; }
    public decimal Balance { get; private set; }

    public void Deposit(decimal amount)
    {
        if (amount &lt;= 0) throw new ArgumentOutOfRangeException(nameof(amount));
        Balance += amount;
    }
}
</code></pre>
<table>
<thead>
<tr>
<th>Modifier</th>
<th>Accessibility</th>
</tr>
</thead>
<tbody><tr>
<td><code>public</code></td>
<td>Unrestricted, within the containing type’s accessibility</td>
</tr>
<tr>
<td><code>private</code></td>
<td>Within the declaring type</td>
</tr>
<tr>
<td><code>protected</code></td>
<td>Within the declaring type and derived types</td>
</tr>
<tr>
<td><code>internal</code></td>
<td>Within the same assembly</td>
</tr>
<tr>
<td><code>protected internal</code></td>
<td>Same assembly or derived types</td>
</tr>
<tr>
<td><code>private protected</code></td>
<td>Declaring type and derived types in the same assembly</td>
</tr>
</tbody></table>
<p><code>sealed</code> prevents inheritance. Primary constructor parameters do not automatically become public properties on ordinary classes. <code>required</code> does not validate the supplied value.</p>
<hr />
<h2>Structs, records, and equality</h2>
<p>A <code>struct</code> is a value type: assignment copies its value. Records generate value-based equality. A plain <code>record</code> is a reference type; a <code>record struct</code> is a value type.</p>
<pre><code class="language-csharp">var original = new Person("Ada", 36);
var updated = original with { Age = 37 };
Console.WriteLine(original == new Person("Ada", 36));
Console.WriteLine(updated);
var point = new Point(1, 2);
var copy = point with { X = 5 };
Console.WriteLine($"{point} / {copy}");

public record Person(string Name, int Age);
public readonly record struct Point(int X, int Y);
</code></pre>
<p><code>with</code> makes a shallow copy. Reference-type members remain shared, so records do not guarantee deep immutability. Value types can also contain reference-type fields whose referenced objects remain shared after copying.</p>
<hr />
<h2>Inheritance and interfaces</h2>
<p>A class can inherit one base class and implement multiple interfaces. Interfaces express shared contracts.</p>
<pre><code class="language-csharp">IShape shape = new Circle(3);
Console.WriteLine(shape.Area);
Animal animal = new Dog();
animal.Speak();

public interface IShape
{
    double Area { get; }
}
public sealed class Circle(double radius) : IShape
{
    public double Area =&gt; Math.PI * radius * radius;
}
public abstract class Animal
{
    public abstract void Speak();
}
public sealed class Dog : Animal
{
    public override void Speak() =&gt; Console.WriteLine("Woof");
}
</code></pre>
<p>Use <code>virtual</code> for an overridable method with a base implementation and <code>override</code> to override it. This differs from hiding a member with <code>new</code>.</p>
<hr />
<h2>Enums and flags</h2>
<p>Enums represent named integer values. For flags, assign values to individual bits.</p>
<pre><code class="language-csharp">Access access = Access.Read | Access.Write;
Console.WriteLine(access.HasFlag(Access.Read));
Console.WriteLine((access &amp; Access.Write) != 0);
Console.WriteLine(Enum.IsDefined(Status.Ready));

public enum Status { Unknown, Ready, Done }
[Flags]
public enum Access { None = 0, Read = 1, Write = 2, Execute = 4 }
</code></pre>
<p>Casting an integer can create an undefined enum value. Validate external input. <code>Enum.IsDefined</code> does not accept a flag combination unless that exact value is declared.</p>
<hr />
<h2>Generics</h2>
<p>Type parameters let you reuse algorithms and data structures while retaining type safety. <code>where</code> constrains the supported types.</p>
<pre><code class="language-csharp">Console.WriteLine(Max(3, 7));
var box = new Box&lt;string&gt;("hello");
Console.WriteLine(box.Value);

static T Max&lt;T&gt;(T left, T right) where T : IComparable&lt;T&gt;
    =&gt; left.CompareTo(right) &gt;= 0 ? left : right;

public sealed class Box&lt;T&gt;(T value)
{
    public T Value { get; } = value;
}
</code></pre>
<p>Common constraints include <code>class</code>, <code>struct</code>, <code>notnull</code>, interfaces, and <code>new()</code>. The <code>new()</code> constraint requires a public parameterless constructor and follows other ordinary constraints.</p>
<hr />
<h2>Lambdas, delegates, and events</h2>
<p><code>Func&lt;...&gt;</code> represents a function with a return value; <code>Action&lt;...&gt;</code> represents one without. Lambdas can capture outer variables. Events notify subscribers from a publisher.</p>
<pre><code class="language-csharp">int factor = 2;
Func&lt;int, int&gt; multiply = value =&gt; value * factor;
factor = 3;
Console.WriteLine(multiply(4));
Action&lt;string&gt; print = message =&gt; Console.WriteLine(message);
print("Ready");

var counter = new Counter();
EventHandler handler = (_, _) =&gt; Console.WriteLine("Changed");
counter.Changed += handler;
counter.Increment();
counter.Changed -= handler;

public sealed class Counter
{
    public int Value { get; private set; }
    public event EventHandler? Changed;
    public void Increment()
    {
        Value++;
        Changed?.Invoke(this, EventArgs.Empty);
    }
}
</code></pre>
<p>A capture retains the variable, not a snapshot of its value. Unsubscribe when a subscription to a long-lived publisher is no longer needed. Use <code>static</code> on a lambda that should not capture outer state.</p>
<hr />
<h2>LINQ</h2>
<p>LINQ expresses filtering, projection, and aggregation over data sources. It supports method syntax and query syntax.</p>
<pre><code class="language-csharp">int[] numbers = [1, 2, 3, 4, 5];
var query = numbers.Where(n =&gt; n % 2 == 0).Select(n =&gt; n * 10);
int[] result = query.ToArray();
Console.WriteLine(string.Join(", ", result));
Console.WriteLine(numbers.Any(n =&gt; n &gt; 4));
Console.WriteLine(numbers.All(n =&gt; n &gt; 0));
Console.WriteLine(numbers.Sum());
Console.WriteLine(numbers.FirstOrDefault(n =&gt; n &gt; 10, -1));

var descending = from n in numbers
                 where n &gt;= 3
                 orderby n descending
                 select n;
Console.WriteLine(string.Join(", ", descending));
foreach (var group in numbers.GroupBy(n =&gt; n % 2))
    Console.WriteLine($"{group.Key}: {group.Count()}");
</code></pre>
<table>
<thead>
<tr>
<th>Operation</th>
<th>Common methods</th>
</tr>
</thead>
<tbody><tr>
<td>Filter and project</td>
<td><code>Where</code>, <code>Select</code>, <code>SelectMany</code></td>
</tr>
<tr>
<td>Sort</td>
<td><code>OrderBy</code>, <code>OrderByDescending</code>, <code>ThenBy</code></td>
</tr>
<tr>
<td>First, last, single</td>
<td><code>First</code>, <code>Last</code>, <code>Single</code> and their <code>OrDefault</code> variants</td>
</tr>
<tr>
<td>Limit results</td>
<td><code>Take</code>, <code>Skip</code>, <code>TakeWhile</code></td>
</tr>
<tr>
<td>Aggregate</td>
<td><code>Count</code>, <code>Sum</code>, <code>Average</code>, <code>Min</code>, <code>Max</code>, <code>Aggregate</code></td>
</tr>
<tr>
<td>Set operations</td>
<td><code>Distinct</code>, <code>Union</code>, <code>Intersect</code>, <code>Except</code></td>
</tr>
<tr>
<td>Materialize</td>
<td><code>ToArray</code>, <code>ToList</code>, <code>ToDictionary</code></td>
</tr>
</tbody></table>
<p><code>Where</code> and <code>Select</code> usually run when enumerated (deferred execution). Enumerating again repeats the work; materialize when you need to retain the results. <code>SingleOrDefault</code> still throws for multiple matches. <code>ToDictionary</code> throws on duplicate keys. An <code>IQueryable&lt;T&gt;</code> provider may translate a query to SQL or another language, so its execution rules differ from in-memory LINQ.</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/linq/get-started/introduction-to-linq-queries">Official guide — LINQ queries</a></p>
<hr />
<h2>Iterators and yield</h2>
<p>Use <code>yield return</code> to produce an iterator’s elements one at a time without first storing them in an array.</p>
<pre><code class="language-csharp">foreach (int value in CountUp(3))
    Console.WriteLine(value);

static IEnumerable&lt;int&gt; CountUp(int count)
{
    for (int i = 0; i &lt; count; i++)
        yield return i;
}
</code></pre>
<p>Iterator bodies normally execute, and may throw, during enumeration rather than at the initial method call. <code>yield break</code> ends enumeration.</p>
<hr />
<h2>Exception handling</h2>
<p>Catch specific exceptions you can handle. Use <code>finally</code> or <code>using</code> to release resources.</p>
<pre><code class="language-csharp">try
{
    Console.WriteLine(ParsePositive("-1"));
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine(ex.ParamName);
}
catch (FormatException)
{
    Console.WriteLine("Invalid number");
}
finally
{
    Console.WriteLine("Finished");
}

static int ParsePositive(string text)
{
    int value = int.Parse(text);
    if (value &lt;= 0)
        throw new ArgumentOutOfRangeException(nameof(text), "Must be positive.");
    return value;
}
</code></pre>
<p>Use <code>throw;</code> to rethrow while preserving the original stack trace. <code>throw ex;</code> resets it. For expected input failures, consider APIs such as <code>TryParse</code> instead of using exceptions for routine branching.</p>
<hr />
<h2>Using and resource management</h2>
<p>The GC manages memory, but resources such as files and connections need timely cleanup. <code>using</code> calls <code>IDisposable.Dispose</code> when its scope ends.</p>
<pre><code class="language-csharp">using var stream = new MemoryStream();
using (var writer = new StreamWriter(stream, leaveOpen: true))
{
    writer.Write("hello");
}
stream.Position = 0;
using var reader = new StreamReader(stream);
Console.WriteLine(reader.ReadToEnd());
</code></pre>
<p>Use <code>await using</code> for asynchronous cleanup through <code>IAsyncDisposable</code>. This differs from a <code>using</code> directive that imports a namespace.</p>
<hr />
<h2>Async, await, and cancellation</h2>
<p>Async methods commonly return <code>Task</code> or <code>Task&lt;T&gt;</code>. When an operation is incomplete, <code>await</code> can yield control to the caller. The <code>async</code> keyword does not itself start a new thread.</p>
<pre><code class="language-csharp">using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2));
try
{
    Task&lt;int&gt; first = WorkAsync(1, cts.Token);
    Task&lt;int&gt; second = WorkAsync(2, cts.Token);
    int[] results = await Task.WhenAll(first, second);
    Console.WriteLine(string.Join(", ", results));
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
    Console.WriteLine("Canceled");
}

static async Task&lt;int&gt; WorkAsync(int value, CancellationToken cancellationToken)
{
    await Task.Delay(20, cancellationToken);
    return value * 2;
}
</code></pre>
<p>Cancellation is cooperative. Pass the token to downstream APIs and call <code>ThrowIfCancellationRequested()</code> in CPU work where appropriate. <code>Task.WhenAll</code> waits for every task; a failure does not automatically cancel the others.</p>
<p>Avoid blocking with <code>.Result</code> or <code>.Wait()</code> and propagate <code>await</code> through callers. Usually reserve <code>async void</code> for event handlers. Use asynchronous APIs for I/O; consider <code>Task.Run</code> when CPU-intensive work needs to run on another thread.</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/">Official guide — asynchronous programming</a></p>
<hr />
<h2>Async streams</h2>
<p><code>IAsyncEnumerable&lt;T&gt;</code> produces elements asynchronously. Enumerate it with <code>await foreach</code>.</p>
<pre><code class="language-csharp">using System.Runtime.CompilerServices;

using var cts = new CancellationTokenSource();
await foreach (int value in ReadAsync(cts.Token))
    Console.WriteLine(value);

static async IAsyncEnumerable&lt;int&gt; ReadAsync(
    [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
    for (int i = 0; i &lt; 3; i++)
    {
        await Task.Delay(10, cancellationToken);
        yield return i;
    }
}
</code></pre>
<hr />
<h2>Concurrency and synchronization</h2>
<p>Synchronize updates to shared state. Use <code>Interlocked</code> for simple counters and <code>lock</code> to protect a group of operations.</p>
<pre><code class="language-csharp">int count = 0;
Parallel.For(0, 1_000, _ =&gt; Interlocked.Increment(ref count));
Console.WriteLine(count);

var gate = new System.Threading.Lock();
List&lt;int&gt; values = [];
Parallel.For(0, 10, i =&gt;
{
    lock (gate)
    {
        values.Add(i);
    }
});
Console.WriteLine(values.Count);
</code></pre>
<p>You cannot <code>await</code> inside a <code>lock</code>. For asynchronous concurrency limits, use <code>SemaphoreSlim.WaitAsync</code> and release in <code>finally</code>. Concurrent collections do not automatically make a sequence of multiple operations atomic.</p>
<hr />
<h2>Span and Memory</h2>
<p><code>Span&lt;T&gt;</code> is a view over contiguous memory; slicing it does not copy elements. <code>ReadOnlySpan&lt;T&gt;</code> prevents writes through that view.</p>
<pre><code class="language-csharp">int[] values = [1, 2, 3, 4];
Span&lt;int&gt; middle = values.AsSpan(1, 2);
middle[0] = 20;
Console.WriteLine(values[1]);
ReadOnlySpan&lt;char&gt; prefix = "hello".AsSpan(0, 2);
Console.WriteLine(prefix.ToString());
</code></pre>
<p><code>Span&lt;T&gt;</code> is a <code>ref struct</code>: it cannot be stored in an ordinary class field or used across an <code>await</code> boundary. Consider <code>Memory&lt;T&gt;</code> for those lifetimes. A readonly view does not prevent other code from modifying the underlying array.</p>
<hr />
<h2>Standard library quick reference</h2>
<p>Frequently used types and namespaces.</p>
<table>
<thead>
<tr>
<th>Purpose</th>
<th>Type or namespace</th>
</tr>
</thead>
<tbody><tr>
<td>Build strings</td>
<td><code>System.Text.StringBuilder</code></td>
</tr>
<tr>
<td>Regular expressions</td>
<td><code>System.Text.RegularExpressions.Regex</code></td>
</tr>
<tr>
<td>Dates and durations</td>
<td><code>DateTimeOffset</code>, <code>DateOnly</code>, <code>TimeOnly</code>, <code>TimeSpan</code></td>
</tr>
<tr>
<td>Files and paths</td>
<td><code>System.IO.File</code>, <code>Directory</code>, <code>Path</code></td>
</tr>
<tr>
<td>JSON</td>
<td><code>System.Text.Json.JsonSerializer</code></td>
</tr>
<tr>
<td>HTTP</td>
<td><code>System.Net.Http.HttpClient</code></td>
</tr>
<tr>
<td>UUIDs</td>
<td><code>Guid</code></td>
</tr>
<tr>
<td>Non-cryptographic randomness</td>
<td><code>Random.Shared</code></td>
</tr>
<tr>
<td>Cryptographic randomness</td>
<td><code>System.Security.Cryptography.RandomNumberGenerator</code></td>
</tr>
<tr>
<td>Concurrent collections</td>
<td><code>System.Collections.Concurrent</code></td>
</tr>
<tr>
<td>Async queues</td>
<td><code>System.Threading.Channels</code></td>
</tr>
<tr>
<td>Elapsed time</td>
<td><code>System.Diagnostics.Stopwatch</code></td>
</tr>
</tbody></table>
<h3>Dates and durations</h3>
<p>Use UTC or an explicit offset for stored or transmitted timestamps, then convert for display.</p>
<pre><code class="language-csharp">using System.Globalization;

DateTimeOffset now = DateTimeOffset.UtcNow;
string encoded = now.ToString("O", CultureInfo.InvariantCulture);
DateTimeOffset restored = DateTimeOffset.Parse(encoded, CultureInfo.InvariantCulture);
DateOnly date = new(2026, 9, 14);
TimeOnly time = new(9, 30);
TimeSpan duration = TimeSpan.FromMinutes(45);
Console.WriteLine($"{restored:O}, {date:yyyy-MM-dd}, {time:HH:mm}, {duration}");
</code></pre>
<p><code>DateTimeOffset</code> stores an offset, not a time zone’s rules. Use <code>TimeZoneInfo</code> for conversions involving daylight saving time and other zone rules.</p>
<h3>Files and paths</h3>
<p>This example creates a temporary file, reads and writes it, then deletes it.</p>
<pre><code class="language-csharp">string path = Path.GetTempFileName();
try
{
    await File.WriteAllTextAsync(path, "hello");
    string text = await File.ReadAllTextAsync(path);
    Console.WriteLine(text);
    Console.WriteLine(Path.GetFileName(path));
}
finally
{
    File.Delete(path);
}
</code></pre>
<p>Process large files incrementally with streams or <code>File.ReadLines</code>. <code>Path.Combine</code> joins paths; it does not validate that external input stays inside an allowed directory.</p>
<h3>JSON</h3>
<p>Use the built-in <code>System.Text.Json</code> APIs to serialize and deserialize data.</p>
<pre><code class="language-csharp">using System.Text.Json;

var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
var person = new Person("Ada", 36);
string json = JsonSerializer.Serialize(person, options);
Console.WriteLine(json);
Person restored = JsonSerializer.Deserialize&lt;Person&gt;(json, options)
    ?? throw new JsonException("Expected a person.");
Console.WriteLine(restored.Name);

public record Person(string Name, int Age);
</code></pre>
<p>Ordinary defaults match property names case-sensitively; web defaults differ. Validate business requirements after deserialization as well.</p>
<h3>HTTP</h3>
<p>This example requires network access. Reuse <code>HttpClient</code> for an appropriate application lifetime, or manage it with <code>IHttpClientFactory</code> in a DI-based application.</p>
<pre><code class="language-csharp">using System.Net;

using var handler = new SocketsHttpHandler
{
    PooledConnectionLifetime = TimeSpan.FromMinutes(2),
    AutomaticDecompression = DecompressionMethods.All
};
using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(10) };
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
using var response = await client.GetAsync("https://example.com/", cts.Token);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync(cts.Token));
</code></pre>
<p>This console example disposes the client on exit. Avoid creating and disposing a client per request in a long-running application. Handle HTTP failures, connection errors, timeouts, and cancellation according to your application’s requirements.</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient-guidelines">Official guide — HttpClient guidelines</a></p>
<hr />
<h2>Namespaces, projects, and NuGet</h2>
<p>Namespaces organize type names. The following is a file in a class library, not an executable <code>Program.cs</code> example.</p>
<pre><code class="language-csharp">namespace Sample.Library;

public static class Calculator
{
    public static int Add(int left, int right) =&gt; left + right;
}
</code></pre>
<p>A file-scoped namespace applies to the whole file. <code>using Sample.Library;</code> shortens type names, but using another project also requires a project reference.</p>
<h3>CLI commands</h3>
<p>These commands create a separate solution for the examples. In .NET 10, <code>dotnet new sln</code> creates a <code>.slnx</code> file by default.</p>
<pre><code class="language-bash">dotnet new sln -n CheatSheet
dotnet new classlib -n Sample.Library --framework net10.0
dotnet new console -n Sample.App --framework net10.0
dotnet sln CheatSheet.slnx add Sample.Library/Sample.Library.csproj Sample.App/Sample.App.csproj
dotnet reference add Sample.Library/Sample.Library.csproj --project Sample.App/Sample.App.csproj
dotnet restore CheatSheet.slnx
dotnet build CheatSheet.slnx
dotnet format CheatSheet.slnx --verify-no-changes
dotnet publish Sample.App/Sample.App.csproj -c Release
</code></pre>
<p>Add a NuGet package with <code>dotnet package add PACKAGE --project PROJECT_PATH</code>. Check its official NuGet page for stable releases and supported frameworks before adopting it. Use <code>dotnet package list --outdated</code> to check for updates. Pin package and SDK versions when reproducibility matters.</p>
<hr />
<h2>Testing</h2>
<p>Add an MSTest project to the solution above. The template configures the test packages. This example explicitly selects <a href="https://www.nuget.org/packages/MSTest/4.4.0">MSTest 4.4.0</a>.</p>
<pre><code class="language-bash">dotnet new mstest -n Sample.Tests --framework net10.0
dotnet package add MSTest --version 4.4.0 --project Sample.Tests/Sample.Tests.csproj
dotnet sln CheatSheet.slnx add Sample.Tests/Sample.Tests.csproj
dotnet reference add Sample.Library/Sample.Library.csproj --project Sample.Tests/Sample.Tests.csproj
dotnet test CheatSheet.slnx
</code></pre>
<h3>Test code</h3>
<p>Place the <code>Calculator</code> shown above in <code>Sample.Library</code>, then replace the generated test file in the test project with this code.</p>
<pre><code class="language-csharp">using Microsoft.VisualStudio.TestTools.UnitTesting;
using Sample.Library;

namespace Sample.Tests;

[TestClass]
public sealed class CalculatorTests
{
    [TestMethod]
    [DataRow(2, 3, 5)]
    [DataRow(-2, 2, 0)]
    [DataRow(0, 0, 0)]
    public void Add_ReturnsSum(int left, int right, int expected)
    {
        Assert.AreEqual(expected, Calculator.Add(left, right));
    }
}
</code></pre>
<p>This block belongs in the MSTest project and cannot run as a standalone console application. Run <code>dotnet test CheatSheet.slnx</code> again after the changes. Async tests should return <code>async Task</code> and await the operation.</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-csharp-with-mstest">Official guide — C# and MSTest</a></p>
<hr />
<h2>C# 14 syntax</h2>
<p>C# 14 adds extension members, field-backed properties, and null-conditional assignment, among other features. Here are representative examples.</p>
<pre><code class="language-csharp">Console.WriteLine("hello".IsLong);
var person = new Person();
person.Name = " Ada ";
Console.WriteLine(person.Name);
Person? missing = null;
missing?.Name = "Grace";
Console.WriteLine(nameof(List&lt;&gt;));

public static class TextExtensions
{
    extension(string text)
    {
        public bool IsLong =&gt; text.Length &gt;= 5;
    }
}
public sealed class Person
{
    public string Name
    {
        get;
        set =&gt; field = value.Trim();
    } = "";
}
</code></pre>
<p>Null-conditional assignment skips evaluation of the right-hand side when the receiver is null. <code>field</code> refers to a compiler-generated backing field. The existing <code>this</code> extension-method syntax remains supported.</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-14">Official reference — what’s new in C# 14</a></p>
<hr />
<h2>Tips and common mistakes</h2>
<ul>
<li>Losing fractions in integer division: convert at least one operand to a floating-point type or <code>decimal</code> before dividing.</li>
<li>Assuming <code>==</code> always means the same thing: ordinary classes default to reference equality, records use value equality, and strings compare content. Use <code>SequenceEqual</code> to compare array elements.</li>
<li>Relying on nullable <code>!</code>: it does not check for null at runtime. Validate input.</li>
<li>Enumerating LINQ repeatedly: watch for deferred execution and retain results with <code>ToList</code> or similar when needed.</li>
<li>Modifying a <code>List&lt;T&gt;</code> during <code>foreach</code>: use <code>RemoveAll</code> or project into another collection.</li>
<li>Forgetting to await: observe task completion and exceptions with <code>await</code>.</li>
<li>Treating <code>async</code> as parallelism: distinguish asynchronous I/O from parallel CPU work.</li>
<li>Generating secrets with <code>Random</code>: use <code>RandomNumberGenerator</code> for cryptographic purposes.</li>
<li>Storing <code>DateTime.Now</code> without time zone context: use UTC or an explicit offset.</li>
<li>Assuming records or <code>readonly</code> guarantee deep immutability: referenced objects can still be mutable.</li>
</ul>
<hr />
<h2>Official references</h2>
<ul>
<li><a href="https://learn.microsoft.com/en-us/dotnet/csharp/">C# documentation</a></li>
<li><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/">Language reference</a></li>
<li><a href="https://learn.microsoft.com/en-us/dotnet/api/">.NET API browser</a></li>
<li><a href="https://learn.microsoft.com/en-us/dotnet/core/tools/">.NET CLI</a></li>
<li><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version">Configure the C# language version</a></li>
</ul>
]]></content:encoded></item></channel></rss>