Re:Effective Rust
by spion on Thursday June 15, 2023 @03:39PM
(#36345429)
Its very different from Java.
In Java, the expectations are declared at the callee site, which is a completely wrong place to do it. Only the caller knows whether the situation is expected or not.
Lets say I'm trying to get the element at index 20 of some array-like datastructure.
Lets say that returns a `Result<T, E>`.
Lets add another twist: I've already checked whether the length is > 30 for other resons in that same block. Therefore, I know (if borrowing mechanisms ensure this) that getting the 20th element will not cause an error. In this case I can use
my_obj
.element_at(20)
.expect("Unexpected missing element at index 20 even though number of elements is > 30")
As a caller, something is very wrong in this situation. If so, I can make the choice (doesn't work for all types of programs) to abort immediately.
edit: see other comments in the thread for a more believable quicksort example, where you are getting the element at `len/2` as pivot.
This is a somewhat certain situation. You can also use this in softer situations, like e.g. a program that just can't run if its data file cannot be found in `$PWD` because say, the docker image is always built in a way that includes it. As a caller, its up to you to decide whether this situation is expected / recoverable or not.
You can also decide that you don't know the answer to that and "propagate" the error further by ensuring the function returns a Result<T, E> using the `?` operator.
Rust is one of the rare languages that gets this right.
In Java, the expectations are declared at the callee site, which is a completely wrong place to do it. Only the caller knows whether the situation is expected or not.
Lets say I'm trying to get the element at index 20 of some array-like datastructure.
Lets say that returns a `Result<T, E>`.
Lets add another twist: I've already checked whether the length is > 30 for other resons in that same block. Therefore, I know (if borrowing mechanisms ensure this) that getting the 20th element will not cause an error. In this case I can use
As a caller, something is very wrong in this situation. If so, I can make the choice (doesn't work for all types of programs) to abort immediately.edit: see other comments in the thread for a more believable quicksort example, where you are getting the element at `len/2` as pivot.
This is a somewhat certain situation. You can also use this in softer situations, like e.g. a program that just can't run if its data file cannot be found in `$PWD` because say, the docker image is always built in a way that includes it. As a caller, its up to you to decide whether this situation is expected / recoverable or not.
You can also decide that you don't know the answer to that and "propagate" the error further by ensuring the function returns a Result<T, E> using the `?` operator.
Rust is one of the rare languages that gets this right.