Rust•関数
Rust の関数と暗黙のブロック式戻り値最適化
Rust は式指向言語です。明示的な return を必要とする文指向言語とは異なり、関数ブロック末尾にセミコロンなしで置かれた式は暗黙的に返されます。セミコロンを付けるとユニット型 () を返す文へと変化します。
構文
fn compute_rate(base: u32, multiplier: u32) -> u32 {
base * multiplier // Implicit return: no semicolon!
}
パラメータと値
この構文の主な構成要素と指定可能な値:
| パラメータ | 型 | 説明 |
|---|---|---|
| fn name(args) -> ReturnType | Function Signature | 関数名・型付き引数・戻り値型のアロー(->)を宣言します。 |
| Tail Expression | Optimization | 末尾セミコロンなしでブロックから自動的に返される最終式。 |
| return expr; | Keyword | 関数ブロックの途中に早期リターンを行う際に使用します。 |
そのまま実行できるコード例
Compilra で実行可能Rust をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:
// 1. Implicit tail return expression (no semicolon)
fn calculate_subtotal(unit_price: u32, quantity: u32) -> u32 {
unit_price * quantity // Evaluates and implicitly returns u32
}
// 2. Early return guard pattern alongside implicit tail return
fn apply_cluster_discount(subtotal: u32, tier: &str) -> u32 {
// Early exit guard
if subtotal == 0 {
return 0;
}
// Implicit return from match expression
match tier {
"ENTERPRISE" => subtotal * 80 / 100, // 20% discount
"STARTUP" => subtotal * 90 / 100, // 10% discount
_ => subtotal, // No discount
}
}
// 3. Block expression evaluating inline
fn format_node_spec(cores: u32, memory_gb: u32) -> String {
let spec_score = {
let compute = cores * 100;
let memory = memory_gb * 10;
compute + memory // Implicit block return into spec_score
};
format!("Specs: {} Cores / {} GB (Score: {})", cores, memory_gb, spec_score)
}
fn main() {
println!("=== Rust Expression-Oriented Function Architecture ===");
let price = 45;
let qty = 4;
let subtotal = calculate_subtotal(price, qty);
println!("Subtotal: ${}", subtotal);
let enterprise_total = apply_cluster_discount(subtotal, "ENTERPRISE");
println!("Enterprise Tier: ${} (20% off)", enterprise_total);
let startup_total = apply_cluster_discount(subtotal, "STARTUP");
println!("Startup Tier: ${} (10% off)", startup_total);
let node_summary = format_node_spec(8, 32);
println!("{}", node_summary);
}期待される出力:
=== Rust Expression-Oriented Function Architecture === Subtotal: $180 Enterprise Tier: $144 (20% off) Startup Tier: $162 (10% off) Specs: 8 Cores / 32 GB (Score: 1120)
動作のしくみ: ステップ解説
- 2-4 行目: calculate_subtotal は return キーワードもセミコロンも使わず積を暗黙的に返します。
- 7-19 行目: 早期リターンガード(return 0;)と match からの暗黙リターンを併用する例を示します。
- 22-30 行目: ブロック式 { ... } を使って spec_score をインラインで計算・返却する例を示します。
重要ポイント
- Rust ではブロック末尾のセミコロンを省略すると、その式がブロックの値として返されます。
- セミコロンを付けると式が文になり、ユニット型 () に評価されるため型不一致のコンパイルエラーになります。
- return キーワードは関数本体途中での早期終了(ガード節)のために残されています。
- ブロック式 { ... } は値が期待されるあらゆる場所に埋め込めます。
よくある間違い: 末尾式に誤ってセミコロンを付けてしまう
最終行にセミコロンを付けると () を返す文になってしまい、関数が特定の戻り値型を期待している場合にコンパイルエラーとなります。
❌ 誤り
fn add(a: i32, b: i32) -> i32 {
a + b; // Compile Error: expected i32, found ()
}✅ 正しい例
fn add(a: i32, b: i32) -> i32 {
a + b // Correct: no semicolon
}