4 ms·
There was no need for a closure in the above code; it could have been written with "if let" and a couple of extra lines. The use of "and_then" was to avoid writ
by pcwalton 12y ago
There was no need for a closure in the above code; it could have been written with "if let" and a couple of extra lines. The use of "and_then" was to avoid writing that extra code.
I've never once regretted the fact that Rust has no null pointers, which is basically what you're criticizing. Null pointers cause so many bugs that the minor effort saved by having them is in no way worth it.
- Animats 12y agoThe design decisions behind Rust are good ones. The ones that matter here are: 1. Null references are undesirable. Good decision. 2. Exceptions are undesirable. Arguable, but not bad. 3. There should be some way to optionally return a null result from a function. Reasonable enough. 4. Functional composition is good, allowing one to write h(g(f(a))) Standard in most languages. 5. Object method syntax is good, allowing one to write a.f().g().h() to compose functions. Standard in most languages. 6. Types are determined at compile time. Required for speed. 7. Function overloading based on parameter types is bad. There are unintended consequences of these decisions. The Option<T> wrapper type can have a value of None, which is not a type to which methods can be applied. So, for functions that return Option, the common "a.f().g().h()" form won't work. Workarounds are available, but they're either wordy ("'if let' and a couple of extra lines") or obscure (using a closure as shown in the example). It may be better in such cases to avoid an object-oriented style, and do composition as "h(g(f(a)))". If all the functions take Option inputs and return Option outputs, None can be passed through the chain of functions by having each function return None if the input is None. Because Rust doesn't support function overloading for plain functions, the names have to be unique within the namespace, so you can't have both "f(a: f64) => Option<f64>" and "f(a: Option<f64>) => Option<f64>". Although some hack with macros/metaprogramming might allow that, by creating wrappers to pass through None. This is getting to be a lot of machinery to do something that comes up frequently.
- steveklabnik 12y ago> The Option<T> wrapper type can have a value of None, which is not a type to which methods can be applied. This is not true. I'd like you to the playpen, but it would get autokilled let x: Option<i32> = None; x.is_some(); h, f, and g in your examples would need to accept an Option as their arguments, but currently don't. That's why you can't chain them together.