I came across a sample code from rust std doc:
let slice = &[1, 1, 1, 3, 3, 2, 2, 2];
let mut iter = slice.chunk_by(|a, b| a == b);
assert_eq!(iter.next(), Some(&[1, 1, 1][..]));
assert_eq!(iter.next(), Some(&[3, 3][..]));
assert_eq!(iter.next(), Some(&[2, 2, 2][..]));
assert_eq!(iter.next(), None);
And I noticed if I changed it to Some(&[1, 1, 1])
, it wouldn't compile because it's now only a reference to an array, not a slice. I previously thought reference to an array was the same as slice. This is fine, because I looked up the doc and saw this code at the beginning of the page:
// slicing a Vec
let vec = vec![1, 2, 3];
let int_slice = &vec[..];
// coercing an array to a slice
let str_slice: &[&str] = &["one", "two", "three"];
And it says "coercing an array to a slince", which means they're not the same. But then I looked up the doc of Deref
trait, and I didn't found array type implements Deref
trait. Nothing similar actually did so. So how can we coerce array (or a reference to array) into slice if array doesn't implement Deref
? ( Maybe something that includes array type actually implements it. But I'm just not familiar with all the contents of Rust, so if I missed it, please just point it out)