let add_one = |x| x + 1;
let five = add_one(4);
I thought to myself "hmm I wonder what happens if I were to call the code with a float rather than an int?"Answered my question a few paragraphs down. Kudos.
Is it possible to write a generic closure? i.e something that would add 1 to any numeric type.
I absolutely love it when a blog post, talk, or docs like these do that.
Especially during talks. Often the speaker will say something and it will immediately pop up questions in my mind which I really really want to ask but of course I should wait till the end. And then they answer it in the next slide. Perfect :)
To answer your last question, not yet. There was an RFC for this, but it was recently postponed; closures rely heavily on traits and we are in the process of re-doing the internals of the trait system. If I remember the reason correctly.
Incidentally, I just finished the build system stuff today to get the new book shipped on doc.rust-lang.org; that slates it to land in Rust 1.18. It will still be a draft, but this is one more step towards it being finished.
I've never had any issues with it.
It would be nice if we could use ? on the Option
returned from next, but ? only works with Result
values currently. Even if we could use ? on Option
like we can on Result, the value we would get would
be borrowed, and we want to move the String from
the iterator into Config.
It seems remiss to not mention that Option/Result have combinators/adapters too, no? let search = match args.next() {
Some(arg) => arg,
None => return Err("Didn't get a search string"),
};
becomes: let search = args.next().ok_or("Didn't get a search string")?;
I'm not the most fluent in Rust, so please tell me whether the above two snippets are not equivalent in some way.It might actually be a nice segue into a page on the combinators of Option and Result, since functional-style Rust seems to benefit from liberal use of them.
> We're going to sidestep the issue of what, exactly, functional programming is or is not, and instead show off some features of Rust that are similar to features in many languages referred to as functional.
Many people think of "programming with higher order functions" to be a feature of functional languages, and that may be wrong, but it's also okay. The goal is to teach the stuff, not worry about what exacty "functional" means.