2 ms·
Ok, I'm at like 0 knowledge on the Rust side, so bear that in mind. Also, to note that I'm genuinely curious about this answer. Why can't I return an integer o
by bena 1y ago
Ok, I'm at like 0 knowledge on the Rust side, so bear that in mind. Also, to note that I'm genuinely curious about this answer.
Why can't I return an integer on error? What's preventing me from writing Rust like C++?
- tczMUFlmoNk 1y agoYou can write a Rust function that returns `i32` where a negative value indicates an error case. Nothing in Rust prevents you from doing that. But Rust does have facilities that may offer a nicer way of solving your underlying problem. For instance, a common example of the "integer on error" pattern in other languages is `array.index_of(element)`, returning a non-negative index if found or a negative value if not found. In Rust, the return type of `Iterator::position` is instead `Option<usize>`. You can't accidentally forget to check whether it's present. You could still write your own `index_of(&self, element: &T) -> isize /* negative if not found */` if that's your preference. https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.position https://doc.rust-lang.org/std/iter/trait.Iterator.html#metho...
- bonzini 1y agoNothing prevents you, you just get uglier code and more possibility of confusion.