英文:
Difference between [T], &[T]
问题
我想知道 slice ([T])
和 reference to a slice (&[T])
之间的区别。我不明白 slices
是如何成为非固定大小的类型的,编译器不能通过源代码推断出切片的大小吗?
我明白我们需要一个切片的引用才能使其有用,然而,只有当我理解了 slices
是如何非固定大小时,这才有意义。
此外,我想了解 str
和 &str
之间的区别。我知道其中一个是切片,另一个是切片的引用,并且 &str
存储了字符串的起始位置和长度的引用。但我感到困惑的是为什么我们不能单独使用 str
而不加引用。为什么我们不能在 str
切片本身内部存储大小。为什么我们需要一个引用。我来自 C++ 背景,也许使用 C++ 的类型和术语可以澄清这些问题!
英文:
I want to know the difference between a slice ([T])
and a reference to a slice (&[T])
. I do not get how slices
are unsized types, can't the compiler deduce the size of a slice through the source code?
I understand we need a reference to a slice to make it useful however, this would only make sense If I understand how slices
are unsized.
Moreover, I wanted to know the difference between str
and &str
. I know one is a slice and the other is a reference to a slice and that &str
stores a reference to the start of the string and the length as well. But it confuses me as to why we can't use str
alone without the reference. Why can't we store the size within the str
slice itself. Why do we need a reference to it. I come from a c++ background so maybe using c++ types and terminologies can clear things up!
答案1
得分: 5
&[T]
或&str
的引用只是一个指针(和一个长度)。这个指针指向哪里?它指向一些数据。这些数据就是[T]
(或str
),切片本身,实际的数据字节。在C++中没有对应的概念。
由于数据可以是任意长度的,所以我们对[T]
无法做太多操作。我们不能将其作为参数,也不能返回它,它必须始终包装在某种类型的引用中。通常是&
或&mut
,但也可以是Box
、Rc
或Arc
,用于拥有切片。
有时,编译器可以推断切片的大小(例如,当我们通过封闭的常量范围进行切片时)。但切片类型从不编码长度。只有在运行时,引用才会编码长度。这是因为有一些数据可能具有任意运行时确定的长度,就像C++的std::span
或std::string_view
一样。
英文:
The reference, &[T]
or &str
is just a pointer (and a length). Where does this pointer point at? It points at some data. This data is the [T]
(or str
), the slice itself, the actual bytes of the data. There is no correspondance to that in C++.
Since the data can be of any length, there is no much we can do with [T]
. We cannot take it as a parameter, we cannot return it, it always has to be wrapped with some kind of reference. Usually it's &
or &mut
, but it can also be Box
or Rc
or Arc
, for owned slices.
Sometimes, the compiler could infer the slice size (e.g. when we're slicing via a closed constant range). But a slice type never encodes the length. Only a reference to it does, at runtime. This is because it is useful to have some data that can be of any runtime-determined length, like C++'s std::span
or std::string_view
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论