1. 함수 인자로 전달하기
고차 함수는 다른 함수를 인자로 받을 수 있습니다. 예를 들어 Fn-trait을 사용해 함수를 인자로 받는 함수를 정의합니다.
fn apply<F>(f: F, x: i32) -> i32
where
F: Fn(i32) -> i32,
{
f(x)
}
fn main() {
let square = |x| x * x;
let result = apply(square, 5);
println!("The square of 5 is: {}", result); // Output: The square of 5 is: 25
}
2. 함수 반환하기
고차 함수는 다른 함수를 반환할 수 있습니다. 이 경우, 반환 타입을 명시해야 합니다.
fn make_multiplier(factor: i32) -> Box<dyn Fn(i32) -> i32> {
Box::new(move |x| x * factor)
}
fn main() {
let times_two = make_multiplier(2);
let result = times_two(5);
println!("5 times 2 is {}", result); // Output: 5 times 2 is 10
}
3. 클로저 사용하기
클로저를 사용해 고차함수를 구현할 수 있습니다. 클로저는 특정 환경을 캡쳐할 수 있어 유용합니다.
fn apply_to_list<F>(list: &[i32], f: F) -> Vec<i32>
where
F: Fn(i32) -> i32,
{
list.iter().map(|&x| f(x)).collect()
}
fn main() {
let numbers = vec![1,2,3,4,5];
let squared_numbers = apply_to_list(&numbers, |x| x * 2);
println!("{:?}", squared_numbers); // Output: [2, 4, 6, 8, 10]
}
GitHub - Koras02/rust-tutorial: https://thinky.tistory.com/category/Back-End/Rust
https://thinky.tistory.com/category/Back-End/Rust. Contribute to Koras02/rust-tutorial development by creating an account on GitHub.
github.com
LIST
'Back-End > Rust' 카테고리의 다른 글
[Rust] 10장 트레이트 (0) | 2025.03.25 |
---|---|
[Rust] 9장 동시성 (0) | 2025.03.20 |
[Rust] 8장 제네릭 (0) | 2025.03.12 |
[Rust] 7장 모듈 (0) | 2025.03.10 |
[Rust] 6장 에러 처리 (0) | 2025.03.08 |