英文:
Why do we need a reference symbol whenever we create a slice in rust
问题
I'm a bit lost on the concept of slices in Rust. I know that [T] is a contiguous block of elements of type T with an unknown size and we need a pointer to that data to access it. What I don't understand is if we run the following code:
let slice: [u8] = arr[1..3];
Is the compiler trying to access the first and second element from 'arr' and storing it in the stack, but it can't do that since it does not know the size, therefore we are forced to refer to the first and second element from 'arr' using a pointer like this:
let slice: [u8] = &arr[1..3];
Secondly, I don't get what it means when the documentation says that slices are a view onto a contiguous block of memory
.
How is str
(a slice type) a view onto a contiguous block of memory? Isn't &str
(a reference to a slice) a view onto a contiguous block of memory?
I come from a C++ background so it is a bit odd seeing how string and slices work in Rust.
英文:
I'm a bit lost on the concept of slices in rust. I know that [T] is a contiguous block of elements of type T with a unknown size and we need a pointer to that data to access it. What I don't understand is if we run the following code:
let slice: [u8] = arr[1..3];
Is the compiler trying to access the first and second element from 'arr' and storing it in the stack, but it can't do that since it does not know the size, therefore we are forced to refer the first and second element from 'arr' using a pointer like this:
let slice: [u8] = &arr[1..3];
Secondly, I don't get what it means when the documentation says that slices are a view onto a contiguous block of memory
How is str
(a slice type) a view onto a contiguous block of memory? Isn't &str
(a reference to a slice) a view onto a contiguous block of memory?
I come from a C++ background so it is a bit odd seeing how string and slices work in rust
答案1
得分: 1
其次,我不明白文档说“切片是对连续内存块的视图”是什么意思。
你说得对。这里的文档非常令人困惑。它在讨论对切片的引用,因为切片本身不是视图,这可以通过Box<[T]>
的存在来证明。但是,虽然&[T]
的技术上准确的名称是“切片引用”(或“切片引用”、“切片的引用”),文档在许多地方都使用术语“切片”来描述它。
有一个开放的GitHub问题来修复这个术语在这里和其他地方的使用:#101353。
英文:
> Secondly, I don't get what it means when the documentation says that "slices are a view onto a contiguous block of memory"
You're right. The documentation is very confusing here. It is talking about references to slice, because slices themselves are not views, as we can prove by the existence of Box<[T]>
. But while the technically accurate name for &[T]
is "slice reference" (or "slice ref", "reference to slice"), the documentation uses the term "slice" to describe it in many places.
There is an open GitHub issue to fix the terminology here and in other places: #101353.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论