learning-rust icon indicating copy to clipboard operation
learning-rust copied to clipboard

Replace .get().unwrap() with [] indexing

Open jieyouxu opened this issue 5 years ago • 0 comments

https://github.com/lefticus/learning-rust/blob/4651c6a420ee0a1450bcd116c3dc05fe5508d5c2/src/main.rs#L92-L99

In Rust, typically two ways of indexing are used: (1) infallible get; and (2) fallible get.

Infallible Get

Infallible get is done by implementing std::ops::Index, which returns the value if the get is successful, or panics if the get fails. This usually should be used when you either don't want to handle the possibility of failure, or that it shouldn't happen because it would otherwise be a logic error (e.g. you defined invariants on the data structure, or you already checked previously).

Fallible Get

Fallible get is done by defining your get method, which typically returns either an Option<T> or Result<T, E> for your type T and error type E. This way should be used when you want to express that the operation can fail, and/or you want to explicitly handle the possibility of failure and error causes.

What would these lines in idiomatic Rust look like?

There's always ways to make it even better, but a simple change can be made to these lines. Since data on struct Board is simply a Vec<bool>, and std::vec::Vec trivially implements std::ops::Index, you can just do

let index = (Board::wrap_coord(y, self.height) * self.width + Board::wrap_coord(x, self.width)) as usize;
self.data[index]

There's now no need to do the unwrapping dance with the comment that this should never fail since the use of std::ops::Index conveys to the Rust programmer that this either succeeds, or is guaranteed to panic at run-time if there is a logic mistake!

If there is a need (e.g. when one is designing an API) for both infallible get and fallible get, usually both are provided; i.e. the type T implements std::ops::Index for infallible get usage and also provides impl T { pub fn get(&self) -> Option<...> } for fallible get.

jieyouxu avatar Jul 15 '20 09:07 jieyouxu