構造体、列挙型、トレイト
Rust Generics
Write a function or struct once and use it with many types, with no cost at run time.
学べること
- Type parameters
- Trait bounds
- Generic structs
largest<T>
largest(&[3, 9, 4])9largest(&[2.5, 1.5])2.5largest(&['x', 'b'])'x'One definition, many types
Generics let you write code once and use it with different types. A type parameter such as T stands for a type that is chosen where the code is used.
T: PartialOrd + Copy is a trait bound: largest accepts any type that can be compared and copied, so it works with integers, floats and characters. Pair<T> is a generic struct, and its impl block is generic too. The compiler creates a separate version for each type, so generics cost nothing at run time.
重要なポイント
- T stands for a type chosen at the call.
- T: PartialOrd limits T to comparable types.
- The compiler makes a version per type.
実行できる Rust のサンプル
Rust
main.rs
fn largest<T: PartialOrd + Copy>(items: &[T]) -> T {
let mut largest = items[0];
for &item in items {
if item > largest {
largest = item;
}
}
largest
}
#[derive(Debug)]
struct Pair<T> {
left: T,
right: T,
}
impl<T: Copy> Pair<T> {
fn swap(&self) -> Pair<T> {
Pair { left: self.right, right: self.left }
}
}
fn main() {
println!("{}", largest(&[3, 9, 4]));
println!("{}", largest(&[2.5, 1.5]));
println!("{}", largest(&['x', 'b']));
let pair = Pair { left: "a", right: "b" };
println!("{:?}", pair.swap());
}
9
2.5
x
Pair { left: "b", right: "a" }練習
サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。
このレッスンを終えましたか?
学習済みにすると進み具合を記録できます。
進み具合はこのブラウザーに保存されています ログインすると、どのデバイスでも引き継げます。
チャレンジで練習する
このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。
すべてのチャレンジ