Skip to content

Commit 9d59c6b

Browse files
Add help message for missing IndexMut impl
Before this change it simply says "cannot assign to immutable indexed content". This might be confusing for Rust beginners, as implementing two traits for "one operator" is not intuitive.
1 parent 45b48b9 commit 9d59c6b

File tree

1 file changed

+23
-0
lines changed
  • src/librustc_borrowck/borrowck

1 file changed

+23
-0
lines changed

src/librustc_borrowck/borrowck/mod.rs

+23
Original file line numberDiff line numberDiff line change
@@ -881,6 +881,29 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
881881
}
882882
}
883883
}
884+
885+
// We add a special note about `IndexMut`, if the source of this error
886+
// is the fact that `Index` is implemented, but `IndexMut` is not. Needing
887+
// to implement two traits for "one operator" is not very intuitive for
888+
// many programmers.
889+
if err.cmt.note == mc::NoteIndex {
890+
let node_id = self.tcx.hir.hir_to_node_id(err.cmt.hir_id);
891+
let node = self.tcx.hir.get(node_id);
892+
893+
// This pattern probably always matches.
894+
if let hir_map::NodeExpr(
895+
hir::Expr { node: hir::ExprKind::Index(lhs, _), ..}
896+
) = node {
897+
let ty = self.tables.expr_ty(lhs);
898+
899+
db.help(&format!(
900+
"trait `IndexMut` is required to modify indexed content, but \
901+
it is not implemented for {}",
902+
ty
903+
));
904+
}
905+
}
906+
884907
db
885908
}
886909
BorrowViolation(euv::ClosureCapture(_)) => {

0 commit comments

Comments
 (0)