Index trait when out of bounds


#1

Should idiomatic implementation of “Index” trait panic when index is out of bounds? Or is it possible to rewrite code below so that index function returns an Option?

use std::ops::Index;
use std::collections::HashMap;


struct Collection<'a>(HashMap<&'a str, i32>);

impl<'a> Collection<'a> {
  fn new() -> Self {
    let mut hash_map = HashMap::new();
    hash_map.insert("a1", 1);
    hash_map.insert("a2", 2);
    
    Collection(hash_map)
  }
}

impl<'a> Index<&'a str> for Collection<'a> {
  type Output = i32;

  fn index(&self, name: &'a str) -> &Self::Output {
    self.0.get(name).unwrap_or_else(|| {
      panic!("Collection index is out of bounds")
    })
  }
}

fn main() {
  let collection = Collection::new();
  println!("{:?}", collection["a1"]);
  println!("{:?}", collection["a2"]);
  println!("{:?}", collection["a3"]);
}

#2

An idiomatic implementation should panic.


#3

Thank you. I think a line in documentation stating that would be helpful


#4

Yes, I haven’t gotten to writing “real” docs yet.