Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a slice starting at the length of a string not panic?

Tags:

syntax

rust

fn main() {
    let s = String::from("hello");
    let hello = &s[5..];
    println!("{}", hello);
}

Why does this code run without a panic? I think this is a condition where the index goes beyond the size of the content. The output of this code example shows nothing.

like image 508
Anatolii Kosorukov Avatar asked Aug 27 '18 08:08

Anatolii Kosorukov


People also ask

What is string slicing in Python?

String Slicing in Python Python slicing is about obtaining a sub-string from the given string by slicing it respectively from start to end. Python slicing can be done in two ways.

How do I slice a string with steps?

You can slice the string with steps after indicating a start-index and stop-index. By default, the step is 1 but in the following example, the step size is 2.

What is the difference between Slice and splice in C++?

1 Slice () : The slice ( ) method copies a given part of an array and returns that copied part as a new array. It doesn’t change the original array. 2 Splice () : The name of this function is very similar to slice ( ). ... 3 Split ( ) : Slice ( ) and splice ( ) methods are for arrays. ...

How to SLIC a string with negative index in Python?

Here you use the negative index to start slicing from the end of the string. The output will be ‘camp’. You can slice the string with steps after indicating a start-index and stop-index. By default, the step is 1 but in the following example, the step size is 2.


1 Answers

Ranges in Rust do not include the upper bound (unless you use the ..= range constructor). That means that ranges like 2..2 are zero length: "start at 2 and take each element up to, but not including 2". When the length is 5, 5..5 and 5.. are equivalent.

While it doesn't seem to make much sense to start a range past the last element, it is convenient that this works this way. For example, if you were taking ever shrinking ranges:

for i in 0 .. s.len() + 1 {
    println!("slice = {:?}", &s[i ..]);
}

Outputs:

slice = "hello"
slice = "ello"
slice = "llo"
slice = "lo"
slice = "o"
slice = ""

It would be annoying if you had to handle the last, empty slice, case separately.

But going further past the length of the data will cause a panic. There's no reason why you would intentionally have written s[6..6] when the string's length is 5.

like image 101
Peter Hall Avatar answered Nov 29 '22 06:11

Peter Hall