Pre-RFC?: sugar: var 'in' collection


sugar : var ‘in’ collection

Python has an ‘in’ operator that allows to check if an element is inside a collection of some sort via “x in y”. It’s one of the many small niceties Python has.
Similar functionality could be added to Rust by adding some sugar:

var 'in' collection -> desugared: collection.contains(&var)

This would only apply to expressions where a boolean is expected like after an ‘if’-keyword, a boolean variable binding or an expression with type ascription. The contains-method is already defined on many of the standard collection types.

At the same time, one should think about the inverse test.

  • !(x in y)
    would obviously work and wouldn’t need any additional changes.
  • x not in y
    Follows the python example. Necessitates ‘not’ as a keyword (I think) which would be a K.O.-criterion.
  • x !in y
    Not very readable in my opinion.

This construct should be backwards-compatible and is therefore postponeable. contains() methods implemented before it may be incompatible with the corresponding trait for it. I’m not aware of any incompatibilities with current or future features that would come with it.


  • intuitive and readable expression
  • less verbose than .contains(&element)


  • Added complexity
  • Depending on the collection it can be non-obvious what type the element has to be to perform the check. As Rust doesn’t have function overloading there can only be one type that is checkable. However, the same already applies today.
    Example: ‘a’ in “string” (check for char) doesn’t work, but “a” in “string” (check for &str) does.
    Edit: I noticed that both a char and &str are patterns (std::str::Pattern) and can be searched for.


I do nto think this is necessary, I think its nice sugar, but I do not think its sugar that really caters to the users of Rust.

Thank you though :slight_smile: I was thinking about this a while ago myself.


Another disadvantage: could be confused with the new placement syntax.

Also note: D uses !in, I believe, so there’s precedent.


Yet a slice can be indexed using usize, Range, RangeFrom, RangeTo or RangeFull – we do have adequate approximations of overloading.


This is not a classical overload, yet. This is based on trait matching by type bounds.