<예제 코드_1>
fn main() {
// Define and call a thunk
let thunk = || println!("I am a thunk");
thunk();
// Defining a closure and storing it in a variable to be used later
let closure = || {
println!("This is a closure stored in a variable");
};
closure();
}
<예제 코드_2>
fn main() {
// Pass a thunk as an argument to a function
fn call_thunk(thunk: &dyn Fn()) {
thunk();
}
let thunk = || println!("I am a thunk");
call_thunk(&thunk);
// Using a thunk as an argument to a function
fn call_another(thunk: &mut dyn FnMut()) {
thunk();
}
let mut closure = || {
println!("This closure is passed as an argument to a function");
};
call_another(&mut closure);
}
<예제 코드_3>
// Return a thunk from a function
fn main() {
fn return_thunk() -> Box<dyn Fn()> {
Box::new(|| println!("I am a thunk"))
}
let thunk = return_thunk();
thunk();
}
<예제 코드_4>
// Using a thunk to delay evaluation of an expression
fn main() {
let x = 42;
let thunk = || x + 8;
println!("{}", thunk());
}
<참조 1> https://chat.openai.com/chat/
<참조 2>
'Rust' 카테고리의 다른 글
[Rust] Web Server : Multi-Threading 추가 (49일차) (0) | 2023.01.31 |
---|---|
[Rust] Web-Server 제작 (48일차) (0) | 2023.01.30 |
[Rust] 고급 Trait 예제 (46일차) (0) | 2023.01.29 |
[Rust] Pattern : 여러 예제 (45일차) (0) | 2023.01.28 |
댓글