3 ms·
It's fairly idiomatic so you get used to it but if you prefer something a little more C-ish you can write it like that (as a side note the code in TFA forgets t
by simias 9y ago
It's fairly idiomatic so you get used to it but if you prefer something a little more C-ish you can write it like that (as a side note the code in TFA forgets to import std::env and BufWriter):
use std::env::args;
fn main() {
let expletive =
match args().nth(1) {
Some(arg) => arg,
None => "y".into(),
};
loop {
println!("{}", expletive);
}
}
This is the equivalent to the unoptimized C version. I would argue that it's a little more readable too, substituting "loop" instead of the idiomatic "for(;;)" and the more verbose match syntax instead of the ternary (the terser rust equivalent being the `unwrap_or` you seemed to dislike).
Personally I think I'd use the "unwrap_or" version, when you're familiar with the language it's completely transparent, easier to parse and expresses intent better I think. For an outsider I can see why it would look like a strange incantation though (but the same could be said about ternaries or CL's "do" construct for instance).
The only thing I'd deem inelegant here is the `"y".into()`. It's probably not obvious what it does and why it's necessary to somebody not familiar with Rust.
- Annatar 9y agoThat example is indeed more readable, but it still reads like methods on objects which is a fundamental issue for me. Any non trivial program written in an object-oriented paradigm eventually becomes incomprehensible, whereas the functional approach doesn’t rely on the state machine model. Two different approaches. I didn’t care for objects back in 1990 and I certainly care even less for them now. I upvoted your example in appreciation for the effort you went through though.
- simias 9y agoI agree that for these types of constructs a more functional style could look better. That being said the OOP approach as the merit of reading in the proper order: you get your args, pick the 1st and then use that or the default "y" value. If you rewrite this to use function calls instead of methods you end up with something like: (or (cadr (args)) "y") Which is fine if you're used to lisp syntax but it's really a matter of taste at this point.
- deleted 9y ago[deleted]