Skip to content

Syntax for slices #13

Closed
Closed
@nikomatsakis

Description

@nikomatsakis

There is a long discussion on rust-lang/rust#4160 discussing the possibility of adding explicit slice operators to the language. Clearly if this is to be done, it requires an RFC and explicit discussion and approval.

I think the consensus on that thread was for the proposal found in this comment (full disclosure, by me):

  1. Add a Slice trait:

    trait Slice<T> {
        fn as_slice<'a>(&'a self) -> &'a [T];
        fn slice_from(&'a self, from: uint) -> &'a [T];
        fn slice_to(&'a self, to: uint) -> &'a [T];
        fn slice(&'a self, from: uint, to: uint) -> &'a [T];
    }
    
    trait MutSlice<T> : Slice<T> { /* as above but with mut qualifiers */ }
    
  2. Add a slice operator expr[a..b] where a and b are optional.

    • The operator autoderefences, like indexing.
    • For fixed-length vectors, its effect is built-in.
    • For other types, it is translated to a call to the appropriate trait method:
      • expr[..] => expr.as_slice()
      • expr[a..] => expr.slice_from(a)
      • expr[..b] => expr.slice_to(b)
      • expr[a..b] => expr.slice(a, b)
  3. Do we have something for mutable slices? Perhaps expr[mut a..b]? These come up less frequently but nonetheless it seems useful, particularly for fixed-length vectors since otherwise there remains no explicit syntax for slicing one that does not rely on coercion.

I'm still roughly in favor of this, though I think I would change the syntax expr[..] to expr[], just because it's shorter. Note though that with DST one can simply do &*vec to get the as_slice() notation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-langRelevant to the language team, which will review and decide on the RFC.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions