What's [..] mean?

In str document, there is a [..], what's that mean? Thanks!

let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect();
assert_eq!(v, ["2020", "11", "03", "23", "59"]);

It's an array indexing operation. It could also be written like this:

let arr: [char; 5] = ['-', ' ', ':', '@'];
let slice: &[char] = &arr[..];

The purpose of doing this over just &arr is that just doing &arr yields a &[char; 5], not an &[char], and these are not the same types. The compiler will convert the former to the latter automatically in some cases, but not when generics get involved like with the split method.

An alternate way to do the same conversion is to call the .as_slice() method.

7 Likes

Also, .. generally signals a range expression.

4 Likes

Here's the documentation on the full range (..). And there are other ranges too.

let slice = &arr[..]; // all fields
let slice = &arr[1..]; // fields from 1 forward
let slice = &arr[..3]; // three fields: 0, 1, and 2
let slice = &arr[1..3]; // fields 1 and 2
2 Likes

An important trick, here: you can put the dotdot in the search box for the documentation, and the results are helpful https://doc.rust-lang.org/std/index.html?search=..

(This works for most symbols -- like plus, slash, etc.)

6 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.