본문 바로가기
Rust

[Rust] Thunk 예제 (47일차)

by 꾸압 2023. 1. 29.

 

<예제 코드_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>

 

 

댓글