2026-08-23
counter_bumped.rs
#[derive(Default)]
struct Counter {
value: i32,
step: i32,
}
impl Counter {
// write this: an associated function `bumped(step: i32) -> Counter`
// that builds a Counter with the given step (via struct update syntax
// and Default::default() for the rest), then increments it once by
// that step before returning it
}
Counter::bumpedを実装してください。フィールドを全て手で書き並べず、..Default::default()を使うこと。
Reference
impl Counter {
fn bumped(step: i32) -> Counter {
let mut c = Counter { step, ..Default::default() };
c.value += c.step;
c
}
}
Counter { step, ..Default::default() }はstepだけを指定し、残りのフィールド(value)はDefault::default()が返す値(0)から埋めます。増分は++ではなくc.value += c.stepと明示的に書きます——Rustにインクリメント演算子が無いのは、前置と後置で意味が変わる紛らわしさを言語設計として避けたためです。これは参考実装であり、唯一の正解ではありません。