Can anyone plaese explain the expressoin [..]

Hi everyone, I'm currently following the doc for writing a HTTP server in rust, and I been looking at this line of code for so long now trying to figure out what the expression [..] is actually doing. I'm only 3 days into rust so please bare with me if this is trivial.

let buffer = format!("{}", String::from_utf8_lossy(&buffer[..]));

I have also noticed that when removing the said expression, everyting works as expected.
Thanks in advance and have a nice day!

It's a full range, it means "slice the entire buffer". If buffer is already a slice, it's essentially a no-op. If it is something that can coerce to a slice, e.g. if it's a Vec, then it's an equivalent to the Vec::as_slice() trivial conversion.

1 Like

You can use the some_array[42] syntax to index into an object, in this case getting the element at a particular location.

However, this syntax is part of the more general std::ops::Index trait, and that trait can be implemented for any arbitrary index type, not just integers.

What the standard library has done is let you use range expressions (e.g. 2..5 for fixed upper and lower bounds, ..8 for a fixed upper bound, 10.. for a fixed lower bound, .. for an unbounded range) to get a slice of consecutive elements in that range.

Indexing with .. means "give me a slice containing all the elements" and is sometimes used as a shorthand for turning a reference to a fixed-length array (e.g. let buffer = [0_u8; 1024]) into a dynamically-sized slice (&[u8]).

2 Likes

Thank you so much, this is what I thought initially, thanks for the explanation. Appreciate it.

Thank you so much, I now understand it well.