container[index] is actually syntactic sugar for *container.index(index), but only when used as an immutable value. If a mutable value is requested, IndexMut is used instead. This allows nice things such as let value = v[index] if the type of value implements Copy.
pub trait Index<Idx: ?Sized> {
/// The returned type after indexing.
#[stable(feature = "rust1", since = "1.0.0")]
type Output: ?Sized;
/// Performs the indexing (`container[index]`) operation.
#[stable(feature = "rust1", since = "1.0.0")]
fn index(&self, index: Idx) -> &Self::Output;
}
这里是为数组[T]的实现, 调用 indextarit 的index 方法
index: I 类型是 core::ops::range::RangeFull
self此时代表&[i32]切片
调用<<core::ops::range::RangeFull as core::slice::SliceIndex<[T]>>::index>
impl<T, I> ops::Index<I> for [T]
where
I: SliceIndex<[T]>,
{
type Output = I::Output;
#[inline]
fn index(&self, index: I) -> &I::Output {
index.index(self)
}
}
动漫真尼玛胃疼 看完漫画妹妹党61✌️ 心疼姐姐
RangeFull Slice
来看看最简单的切片(slice)
编译器会把数组的地址和长度作为参数, 数组是编译器可确定大小的,还不清楚为什么要把
data.rel.ro
存文件名字符串段传进去调用
core::ops::index
的index
方法先看
Index
tarit, 返回 index 后的类型,包含 index 方法平常用的
container[index]
也不过是*container.index(index)
的语法糖那么这里的
&slice[..]
等于&*slice.index(std::ops::RangeFull)
?这里是为数组
[T]
的实现, 调用index
tarit 的index
方法index: I
类型是core::ops::range::RangeFull
self
此时代表&[i32]
切片调用
<<core::ops::range::RangeFull as core::slice::SliceIndex<[T]>>::index>
Slice
限定的SliceIndex
如下,下面列举了作为 index 应该满足的调用ops::Range
稍微改一下
因为是数组引索,还是调用
impl Index for [T]
,传入数组信息这里有所变化,这里传入的参数多了个
begin
和end
分别处理可变不可变两种情况,可以看到最后还是用转换成用指针操作, 还是用了
unsafe
= =当然还有一些检查
slice
再来看一个迷惑的例子= =别跟我说这是三维数组 (
切片的表示不止
&slice[..]
一种,[T][..]
也能表示 因为[..]
返回一个切片总结
Index
traitimpl<T, I> ops::Index<I> for [T]
数组[T]
实现了引索Index
taritRangeFull
的index
函数,并且`RangeFull
被SliceIndex
限定ops::Range
也差不多 = =例子
比如std 官方例子就很生动了
此时
Nucleotide
相当于FullRange
NucleotideCount
相当于[T]