New Chat
Ctrl
K
Kimi Code 3x Boost
Chat History
Mobile App

Will Rust slice panic?

fn main() { // Will this panic or not? let s : Vec<u8> = vec![0u8; 32]; println!("{:?}", &s[1..=0]); }
This is an interesting Rust question about slice indexing behavior. Let me analyze this code without needing any tools.

Analysis

The code creates a vector of 32 zeros, then tries to print &s[1..=0].
The key question: Will this panic or not?

Answer: Yes, this will panic! 🚨

Here's why:

The Range 1..=0 (Inclusive Range)

In Rust, range bounds have specific rules:
  • start..=end is an inclusive range
  • The critical rule: The start must be ≤ end for the range to be valid
When you write 1..=0:
  • Start = 1
  • End = 0 (inclusive)
Since 1 > 0, this violates the range invariant that start ≤ end.

What Happens

rust
Copy
let s: Vec<u8> = vec![0u8; 32];
println!("{:?}", &s[1..=0]);  // PANIC!
Panic message:
plain
Copy
thread 'main' panicked at 'slice index starts at 1 but ends at 0'

Why Not an Empty Slice?

You might think "1 to 0 is just empty," but Rust's slice indexing doesn't work that way. The bounds are checked before considering what elements would be selected. The range 1..=0 is considered invalid because:
  • Start (1) > End (0)
  • This is always an error, regardless of the vector's contents

Contrast with Valid Empty Ranges

These would not panic (they produce empty slices):
rust
Copy
&s[0..0]      // start == end, valid empty range
&s[1..1]      // start == end, valid empty range  
&s[32..32]    // start == end == len, valid empty range
&s[1..0]      // wait... this also panics! (exclusive range with start > end)
Even 1..0 (exclusive) panics for the same reason.

Summary

Table
Copy
ExpressionResult
s[0..0]✅ Empty slice &[]
s[1..1]✅ Empty slice &[]
s[1..0]❌ Panic (start > end)
s[1..=0]❌ Panic (start > end)
The panic occurs because Rust validates that range bounds are logically ordered before applying them to the slice.