6 ms·
You can write higher-order functions in Rust - in fact, much of the standard library relies on them. What you cannot do is use named and anonymous functions int
by catnaroek 13y ago
You can write higher-order functions in Rust - in fact, much of the standard library relies on them. What you cannot do is use named and anonymous functions interchangeably.
- mpweiher 13y agoyou cannot [..] use named and anonymous functions interchangeably. That seems like a odd restriction/asymmetry. What's the rationale?
- mcpherrinm 13y agoIt is a bit weird, and it's one of the parts of the language still being worked on [1]. What it comes down to is that while they're both bits of machine code being executed, their environments are different. I'm a bit out of date as there's been movement in this area since I've written much "hard core" Rust code, but the basic problem is that what the grandparent poster calls an "anonymous function" is a closure, with a captured environment. Thus said closure has different interactions with lifetimes, memory management, and program safety. Since safety and soundness is one of the primary goals of Rust, problems like this do crop up and are surely what I see as the hardest part of designing a usable language. [1] http://smallcultfollowing.com/babysteps/blog/2013/10/10/fn-types-in-rust/ http://smallcultfollowing.com/babysteps/blog/2013/10/10/fn-t...
- catnaroek 13y agoTo be frank, I am not sure of the specifics. At first I thought it was because anonymous functions have a notion of the lifetime of the variables they close over, which named functions do not. However, taking into account that named functions do not close over anything in first place, this suggests that one should be able to use a named function wherever an anonymous function is expected.
- Touche 13y agoYou can use named functions interchangeably with anonymous functions, it's not just practical because of pointers.
- catnaroek 13y agoI stand corrected. Indeed, this program worked just fine: fn foo() { println("hai") } fn main() { let xs = ~[1,2,3]; for _ in xs.iter() { std::task::spawn(foo) } }
- pcwalton 13y agoYes, you can. Try it: fn add1(x: &int) -> int { *x + 1 } fn main() { println!("{:?}", [ 1, 2, 3, 4, 5 ].map(add1)); }