구조체, 열거형, 트레이트
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 리뷰를 받을 수 있습니다.
모든 챌린지