Calling an on-heap function argument inside a closure

I use rust 0.8.

Why can I do this:

fn add(num: ~int) -> ~fn(int) -> int { |x|
    *num + x
}

but not this:

fn outer(num: ~int) -> ~fn(int) -> int { |x|
    *inner(num) + x
}

fn inner(num: ~int) -> ~int {
    num
}

second failure "with an error: cannot exit the captured external variable in heap closure". What makes a call to a special function?

Is it a concern that an internal function might do something dirty with this box function that static analysis won't catch?

+4
source share
1 answer

. num inner, . , num ( ), .

()

struct Closure { // stores all the captured variables
    num: ~int
}

impl Closure {
    fn call(&self, x: int) -> int { 
        // valid:
        *self.num + x

        // invalid:
        // *inner(self.num) + x
    }
}

, : , self.num - inner ( num). , self , , , self.num , ( ).


- " ", , , ( ), call fn call(self, x: int), .. self, , ( call self ), , *.

* , , . struct Env { x: int }.

+3

All Articles