Kaioh33
Kaioh33

Reputation: 11

What does this line of code in Rust mean?

I was going through rust-by-practice and came across a problem. I have no idea what a particular line of code does. This is the exact piece of code for context:

fn example1() {
    // `T: Trait` is the commonly used way.
    // `T: Fn(u32) -> u32` specifies that we can only pass a closure to `T`.
    struct Cacher<T: Fn(u32) -> u32> {
        calculation: T,
        value: Option<u32>,
    }

    impl<T: Fn(u32) -> u32> Cacher<T> {
        fn new(calculation: T) -> Cacher<T> {
            Cacher {
                calculation,
                value: None,
            }
        }

        fn value(&mut self, arg: u32) -> u32 {
            match self.value {
                Some(v) => v,
                None => {
                    let v = (self.calculation)(arg); // This exact line of code
                    self.value = Some(v);
                    v
                },
            }
        }
    }

    let mut cacher = Cacher::new(|x| x+1);
    assert_eq!(cacher.value(10), __);
    assert_eq!(cacher.value(15), __);
}

Upvotes: 1

Views: 144

Answers (1)

Jeremy Meadows
Jeremy Meadows

Reputation: 2561

The calculation field of Cacher is a closure (type T where T: Fn(u32) -> u32), and that line is calling it with arg as an argument, then assigning the resulting u32 to v. Without the parentheses, let v = self.calculation(arg) will look for a method named calculation, which doesn't exist. The parenthesis force a different order of operations which produces a different result.

Upvotes: 4

Related Questions