Index trait when out of bounds


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);

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"]);


An idiomatic implementation should panic.


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


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