<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>「let」タグの記事一覧｜Rust Tech</title>
	<atom:link href="https://rust-tech.nkhn37.net/tag/let/feed/" rel="self" type="application/rss+xml" />
	<link>https://rust-tech.nkhn37.net</link>
	<description>Rustプログラミング学習サイト</description>
	<lastBuildDate>Fri, 20 Mar 2026 22:44:11 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>

<image>
	<url>https://rust-tech.nkhn37.net/wp-content/uploads/2025/06/cropped-lion-preasure-clear-32x32.png</url>
	<title>「let」タグの記事一覧｜Rust Tech</title>
	<link>https://rust-tech.nkhn37.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>【Rust入門】変数と定数を分かりやすく解説</title>
		<link>https://rust-tech.nkhn37.net/rust-variables-constants/</link>
					<comments>https://rust-tech.nkhn37.net/rust-variables-constants/#respond</comments>
		
		<dc:creator><![CDATA[naoki-hn]]></dc:creator>
		<pubDate>Wed, 09 Jul 2025 20:00:00 +0000</pubDate>
				<category><![CDATA[Rust入門]]></category>
		<category><![CDATA[const]]></category>
		<category><![CDATA[let]]></category>
		<category><![CDATA[mut]]></category>
		<category><![CDATA[イミュータブル]]></category>
		<category><![CDATA[シャドーイング]]></category>
		<category><![CDATA[スコープ]]></category>
		<category><![CDATA[変数]]></category>
		<category><![CDATA[定数]]></category>
		<category><![CDATA[所有権]]></category>
		<guid isPermaLink="false">https://rust-tech.nkhn37.net/?p=282</guid>

					<description><![CDATA[Rustの変数と定数 プログラムを実行していく際には、ある値をコンピューターのメモリ上に格納し、取り出しながら様々な処理を実行していきます。ある値を含む場所のメモリをオブジェクトと呼びます。そして、そのオブジェクトを識別 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading jinr-heading d--bold">Rustの変数と定数</h2>



<p class="wp-block-paragraph">プログラムを実行していく際には、ある値をコンピューターのメモリ上に格納し、取り出しながら様々な処理を実行していきます。ある値を含む場所のメモリをオブジェクトと呼びます。そして、そのオブジェクトを識別するための識別子が必要です。</p>



<p class="wp-block-paragraph">ある値（オブジェクト）を識別子（名前）に束縛することで、<strong><span class="jinr-d--text-color d--marker1 d--bold">変数（variable）</span></strong>を定義します。また、プログラムを実行している最中に値が変更されることのない、あらかじめ決められた値は<strong><span class="jinr-d--text-color d--marker1 d--bold">定数（constant）</span></strong>と呼ばれます。</p>



<p class="wp-block-paragraph">この記事では、Rustにおける変数と定数の扱いや使い方について解説します。</p>



<h3 class="wp-block-heading jinr-heading d--bold">Rustの変数は基本イミュータブルで変更不可</h3>



<p class="wp-block-paragraph">Rustで最初に覚えておいてほしいことは「<strong><span class="jinr-d--text-color d--marker1 d--bold">変数は基本イミュータブルで変更ができない</span></strong>」ということです。他のプログラミング言語を学んできた人は変数の値を変えられることが普通であることが多かったと思いますし、変数という名前から考えると違和感を覚えるかもしれません。</p>



<section class="wp-block-jinr-blocks-simplebox b--jinr-block-container"><div class="b--jinr-block b--jinr-box d--heading-box1  "><div class="a--simple-box-title d--bold">ミュータブルとイミュータブルとは？</div><div class="c--simple-box-inner">
<ul class="wp-block-list jinr-list">
<li>ミュータブル：変更可能で、作成後も内容を変更することができます。</li>



<li>イミュータブル：変更不可能で、一度作られたらその内容を変更することはできません。</li>
</ul>
</div></div></section>



<p class="wp-block-paragraph">例えば、Haskellなどの関数型プログラミング言語は、変数がイミュータブルで、関数も副作用を持たないように設計されているため、参照透過性が高く、同じ入力には常に同じ出力が保証されます。変数の値が変更できないことは、不便に思うかもしれないですが、一方で値が変わらないことが保証されるため、バグがないプログラムを書くことが可能になります。</p>



<p class="wp-block-paragraph">Rustでの変数定義と利用の例を見てみましょう。</p>



<p class="wp-block-paragraph">[<code><a href="https://github.com/nkhn37/rust-tech-sample-source/blob/main/rust-basic/variables_and_constants/examples/immutable.rs" target="_blank" rel="noreferrer noopener">immutable.rs</a></code>]</p>



<pre class="EnlighterJSRAW" data-enlighter-language="rust" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">fn main() {
    let x = 5;
    println!("xの値: {}", x);

    // 以下はエラーとなる
    // x = 6;
}</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【コンパイル結果】
error[E0384]: cannot assign twice to immutable variable `x`
 --> examples\immutable.rs:7:5
  |
2 |     let x = 5;
  |         - first assignment to `x`
...
7 |     x = 6;
  |     ^^^^^ cannot assign twice to immutable variable
  |
help: consider making this binding mutable
  |
2 |     let mut x = 5;
  |         +++</pre>



<p class="wp-block-paragraph">Rustでは、変数の定義に <code><strong><span class="jinr-d--text-color d--marker1 d--bold">let</span></strong></code> キーワードを使い、変数 <code>x</code> に <code>=</code> で値を設定します。「<code>let x = 5;</code>」のような記載を「文」といい、Rustでは、<strong><span class="jinr-d--text-color d--marker1 d--bold">値を束縛する</span></strong>という表現をします。また、変数はスネークケース（<code>snake_case</code>）という小文字単語をアンダースコアでつなぐ形式にするのが通例です。</p>



<p class="wp-block-paragraph">上記例で一度定義した x に対して、<code>x = 6;</code> という形で値を変更した場合には、コンパイルの際に「<code>cannot assign twice to immutable variable</code>」というようなエラーが発生します(コメントアウトしているため外して実行してみてください)。これは、イミュータブルな変数に2度、値を設定しようとしているというエラーです。</p>



<p class="wp-block-paragraph">ただし、コンパイル結果の <code>help:</code> の記載を見てみると分かりますが、Rustでは値を変更するための方法があります。以降ではその方法を見てみましょう。</p>



<h3 class="wp-block-heading jinr-heading d--bold">変更するにはミュータブル <code>mut</code> の指定が必要</h3>



<p class="wp-block-paragraph">Rustで値を変更する変数の場合には、<code>let mut</code> という形で <code><strong><span class="jinr-d--text-color d--marker1 d--bold">mut</span></strong></code> キーワードを指定します。</p>



<p class="wp-block-paragraph">[<code><a href="https://github.com/nkhn37/rust-tech-sample-source/blob/main/rust-basic/variables_and_constants/examples/mutable.rs" target="_blank" rel="noreferrer noopener">mutable.rs</a></code>]</p>



<pre class="EnlighterJSRAW" data-enlighter-language="rust" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">fn main() {
    // ミュータブルな変数として定義する
    let mut x = 5;
    println!("xの値: {}", x);

    // ミュータブルな変数に値を再度設定する
    x = 6;
    println!("xの値: {}", x);
}</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
xの値: 5
xの値: 6</pre>



<p class="wp-block-paragraph">上記の結果を見てみると分かるように、今度は <code>x</code> の値を変更してもエラーは発生せずに実行を完了することができます。</p>



<section class="wp-block-jinr-blocks-iconbox b--jinr-block b--jinr-iconbox"><div class="d--simple-iconbox1 ">
			<i class="jif jin-ifont-v2bulb" aria-hidden="true"></i>
			<div class="a--jinr-iconbox">
<p class="wp-block-paragraph"><strong>【ポイント】</strong></p>



<p class="wp-block-paragraph">Rust の変数が基本的にイミュータブルであるのはメモリ安全性（データ競合の防止）のためです。一方で、厳格すぎると開発効率の低下につながってしてしまうため、<code>mut</code> を使うことで明示的に「この変数は変更可能です」と定義して使えるようにすることで、安全性と開発効率のバランスをとっています。</p>
</div>
		</div></section>



<h3 class="wp-block-heading jinr-heading d--bold">シャドーイング</h3>



<p class="wp-block-paragraph">Rustでは、一度定義した変数を再度 <code>let</code> を用いて再定義することができます。このことを「<strong><span class="jinr-d--text-color d--marker1 d--bold">シャドーイング（shadowing）</span></strong>」と言います。</p>



<h4 class="wp-block-heading jinr-heading d--bold">シャドーイングの基本</h4>



<p class="wp-block-paragraph">以下の例では、一度 <code>let x = 5;</code> で定義した変数 x について、再度 <code>let x = 10;</code> で再定義しています。</p>



<p class="wp-block-paragraph">[<code><a href="https://github.com/nkhn37/rust-tech-sample-source/blob/main/rust-basic/variables_and_constants/examples/shadowing.rs" target="_blank" rel="noreferrer noopener">shadowing.rs</a></code>]</p>



<pre class="EnlighterJSRAW" data-enlighter-language="rust" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">fn main () {
    let x = 5;
    println!("xの値: {}", x);

    // xをシャドーイングする
    let x = 10;
    println!("xの値: {}", x);
}</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
xの値: 5
xの値: 10</pre>



<p class="wp-block-paragraph">上記で見たように一度定義した <code>x</code> の値を変更することは、イミュータブルな性質から不可能でした。しかし、今回の例での <code>let</code> を使った再定義は問題なくできます。この時に、もともと定義していた <code>x = 5;</code> を後の定義が覆い隠してしまうことから、シャドーイング（shadowing）と呼ばれるわけです。</p>



<p class="wp-block-paragraph">同じスコープ内では、前に定義した <code>x = 5;</code> の値は二度と使えなくなるため、スコープを抜けたタイミングで <code>5</code> が格納されているメモリ領域は自動で解放されます。</p>



<section class="wp-block-jinr-blocks-simplebox b--jinr-block-container"><div class="b--jinr-block b--jinr-box d--heading-box1  "><div class="a--simple-box-title d--bold">スコープとは？</div><div class="c--simple-box-inner">
<p class="wp-block-paragraph">スコープとは、変数の有効範囲を定めるコードブロック（<code>{}</code>）の範囲のことを言います。Rustでは、変数はスコープ内で有効であり、スコープを抜けると所有権が失われ、自動的にリソース（メモリ）が解放されます。C/C++のように <code>free</code> などで手動でメモリを開放する必要がなく、Rustではこの処理がコンパイラと言語仕様で保証されているため、メモリ解放忘れのバグを防止できます。所有権については、少し難しいのでまた別途取り上げます。</p>
</div></div></section>



<h4 class="wp-block-heading jinr-heading d--bold">異なるスコープでのシャドーイング</h4>



<p class="wp-block-paragraph">異なるスコープでシャドーイングによる変数の再定義をした場合に、どのような挙動になるのかを以下の例で確認してみましょう。</p>



<p class="wp-block-paragraph">[<code><a href="https://github.com/nkhn37/rust-tech-sample-source/blob/main/rust-basic/variables_and_constants/examples/shadowing_other_scope.rs" target="_blank" rel="noreferrer noopener">shadowing_other_scope.rs</a></code>]</p>



<pre class="EnlighterJSRAW" data-enlighter-language="rust" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">fn main () {
    let x = 5;
    println!("xの値: {}", x);
    {
        // 異なるスコープでシャドーイングする
        let x = 10;
        println!("xの値: {}", x);
    }
    println!("xの値: {}", x);
}</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
xの値: 5
xの値: 10
xの値: 5</pre>



<p class="wp-block-paragraph">上記例では、<code>let x = 5;</code> で一度定義した変数を一段深いスコープで <code>let x = 10;</code> で再定義しています。このとき、このスコープ内で <code>x</code> の値は <code>10</code> ですが、スコープを抜けると外側の <code>x = 5;</code> に戻ります。そのため、<code>println!</code> で <code>5</code> が表示されていることが分かります。なお、<code>10</code> が格納されているメモリは、スコープを抜けた際に解放されます。このように異なるスコープ間でのシャドーイングの挙動はよく理解しておきましょう。</p>



<h3 class="wp-block-heading jinr-heading d--bold"><code>const</code> 定数</h3>



<p class="wp-block-paragraph">Rustで定数を定義するためには、<strong><span class="jinr-d--text-color d--marker1 d--bold"><code>const</code></span></strong> キーワードを使用して定義します。</p>



<p class="wp-block-paragraph">定数とはコンパイル時に値が確定しているもので、一度決めたら絶対に変わらない値を定義する際に使用します。例えば、システムで共通に使用するパラメータを定義するような場合です。</p>



<p class="wp-block-paragraph">定数は、大文字のスネークケース（<code>SNAKE_CASE</code>）で定義するのが通例です。定数は関数内でも定義できますが、実際にはプログラム全体で使う値を定義するために、グローバルに定義されることが多いです。</p>



<p class="wp-block-paragraph">定数は以下のように定義して使用します。</p>



<p class="wp-block-paragraph">[<code><a href="https://github.com/nkhn37/rust-tech-sample-source/blob/main/rust-basic/variables_and_constants/examples/constant.rs" target="_blank" rel="noreferrer noopener">constant.rs</a></code>]</p>



<pre class="EnlighterJSRAW" data-enlighter-language="rust" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// 定数を定義 (型注釈は必須)
const MAX_USERS: u32 = 100;

fn main () {
    // 定数を利用
    println!("MAX_USERS: {}", MAX_USERS)
}</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
MAX_USERS: 100</pre>



<p class="wp-block-paragraph">変数と定数の違いの一つとして、<strong><span class="jinr-d--text-color d--marker1 d--bold">型定義が必須である</span></strong>ことがあげられます。変数は型推論がされるため、指定は必須ではありません。上記例では、<code>MAX_USERS: u32 = 100;</code> の <code>: u32</code> という部分が 32ビットの符号なし整数であることを示しています。Rustの標準的な型については、別途取り上げて説明しようと思います。</p>



<p class="wp-block-paragraph">また、コンパイル時に決定する性質であることから、動的に確保されるヒープ領域に格納される型（<code>Vec&lt;T&gt;</code>など）での定義もできません。</p>



<div id="nkhn3-1653190426" class="nkhn3- nkhn3-entity-placement" style="margin-left: auto;margin-right: auto;text-align: center;"><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9478001176347002"
     crossorigin="anonymous"></script>
<ins class="adsbygoogle"
     style="display:block; text-align:center;"
     data-ad-layout="in-article"
     data-ad-format="fluid"
     data-ad-client="ca-pub-9478001176347002"
     data-ad-slot="4670569211"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></div><h2 class="wp-block-heading jinr-heading d--bold">まとめ</h2>



<p class="wp-block-paragraph">この記事では、Rustにおける変数と定数の基本的な使い方について解説しました。</p>



<p class="wp-block-paragraph">Rustの変数はデフォルトでイミュータブル（変更不可）であり、安全性を高めるための設計となっています。一方で、<code>mut</code> キーワードを使うことで明示的に可変な変数も定義できるため、安全性と柔軟性のバランスがとられています。</p>



<p class="wp-block-paragraph">同じ名前の変数を再定義する「シャドーイング」やスコープにより変数の有効範囲が制限される仕組みもRustの所有権やメモリ管理の考え方と密接に関係しています。また、<code>const</code> によってコンパイル時に固定される定数を定義することで、値の意味付けや再利用性を高めることができます。</p>



<p class="wp-block-paragraph">Rustを学び始めたばかりの段階では、このような「変数と定数の基本的なルール」をしっかり理解しておくと、Rustの中心的な概念である所有権やライフタイムなどについても理解しやすくなります。ぜひ基本をしっかりと押さえておいてください。</p>



<section class="wp-block-jinr-blocks-simplebox b--jinr-block-container"><div class="b--jinr-block b--jinr-box d--heading-box8  "><div class="a--simple-box-title d--bold">ソースコード</div><div class="c--simple-box-inner">
<p class="wp-block-paragraph">上記で紹介しているソースコードについては <a href="https://github.com/nkhn37/rust-tech-sample-source/tree/main/rust-basic/variables-and-constants" target="_blank" rel="noreferrer noopener">GitHub</a> にて公開しています。参考にしていただければと思います。</p>
</div></div></section>


<section class="b--jinr-block b--jinr-blogcard d--blogcard-hover-up d--blogcard-style1 d--blogcard-mysite t--round "><div class="a--blogcard-label ef">あわせて読みたい</div><a class="o--blogcard-link t--round" href="https://rust-tech.nkhn37.net/rust-programming-basics/"><div class="c--blogcard-image"><img decoding="async" class="a--blogcard-img-src" width="128" height="72" src="https://rust-tech.nkhn37.net/wp-content/uploads/2025/08/77e7c51961993fb9cb96c02a2311436d-320x180.jpg" alt="Rust プログラミング入門" /></div><div class="a--blogcard-title d--bold">Rust プログラミング入門</div></a></section><div id="nkhn3-3021486293" class="nkhn3-multiplex nkhn3-entity-placement" style="margin-left: auto;margin-right: auto;text-align: center;"><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9478001176347002"
     crossorigin="anonymous"></script>
<ins class="adsbygoogle"
     style="display:block"
     data-ad-format="autorelaxed"
     data-ad-client="ca-pub-9478001176347002"
     data-ad-slot="8958649655"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></div>]]></content:encoded>
					
					<wfw:commentRss>https://rust-tech.nkhn37.net/rust-variables-constants/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Disk: Enhanced  を使用したページ キャッシュ

Served from: rust-tech.nkhn37.net @ 2026-06-05 05:01:31 by W3 Total Cache
-->