book
book copied to clipboard
Slice is NOT reference
- [x] I have checked the latest
main
branch to see if this has already been fixed - [x] I have searched existing issues and pull requests for duplicates
URL to the section(s) of the book with this problem: https://github.com/rust-lang/book/blob/main/src/ch04-03-slices.md
Description of the problem:
According to the Rust compiler (and also Programming Rust), [T]
is called a slice, not &[T]
. The latter is called a fat pointer.
fn main() {
fn test(a: [i32; 2]) {}
let arr = [0,1,2];
let sth = arr[..];
test(sth); /* rustc: mismatched types, expected array `[i32; 2]`, found slice `[{integer}]` */
}
fn mian() {
fn test(a: &[i32]) {}
let arr = [0,1,2];
let sth = &arr[..];
test(sth); /* rustc: mismatched types, expected slice `[i32]`, found `&[{integer}]`*/
}
But in this page https://github.com/rust-lang/book/blob/main/src/ch04-03-slices.md
A string slice is a reference to part of a String, .. a slice that contains a pointer to the byte at index .. This slice has the type &[i32]. It works the same way as string slices do, by storing a reference to the first element and a length.
These statements are just talking about &[T]
, not slices.
Suggested fix: The page mentioned above may need a complete review. I'll help with Chinese translations.
Personally, I just prefer to put extra effort in distinguishing slice and slice reference at the first time, rather than get very confused at what rustc is complaining about many days after that 😜
I think ,the meaning of this reference is that it refers data which is in the heap,not the variable in stack.
@ravelartemis I think ,the meaning of this reference is that it refers data which is in the heap,not the variable in stack.
Yeah, but actually allocation in stack or heap just doesn't matter when talking about slices: We can just allocate an array in stack as we often do, and take a slice (with type [T]
) from it.
Here I just want to clarify that a slice is just a part of the array, not a reference to it. And because the size of that part is unknown at compile time, we create a fixed-sized fat pointer (with type &[T]
) as a reference to that slice, so that we can name it as a variable or pass it as an argument.
For some additional information, here's how Programming Rust defines slices, which I think very accurate:
@Nekomaru-PKU the book is right now.
@Nekomaru-PKU the book is right now.
I'm afraid that the three statements that I mentioned in this issue as inaccurate do still exist in the latest commit on main branch (668c647) and also the book.