如何惯用地要求特征来检索切片
How to idiomatically require a trait to retrieve a slice
我正在研究 a library that operates on [T]
slices。我希望库用户指定一种可以以可变或不可变方式检索切片的类型。
我当前的库定义了 2 个特征
pub trait SliceWrapper<T> {
fn slice(&self) -> &[T];
}
pub trait SliceWrapperMut<T> {
fn slice_mut (&mut self) -> &mut [T];
}
但是名称 slice
和 slice_mut
似乎是任意的,而不是核心 Rust 库中的某个地方。
有没有我应该要求的特质,比如 Into::<&mut [T]>
?
我担心 Into
会使用该类型而不仅仅是引用它,所以我不能简单地要求调用者类型实现 core::convert::Into
,可以吗?
回答这个问题的最简单方法是查看现有类型的文档,这些类型或多或少可以满足您的需求。这听起来像是 Vec
会做的,那么为什么不看看 documentation for Vec
?
如果您在其中搜索 -> &
,您会发现许多 return 借用切片的方法:
Vec::as_slice
Borrow::borrow
Index::<Range<usize>>::index
(加上 RangeTo<usize>
、RangeFrom<usize>
、RangeFull
、RangeInclusive<usize>
和 RangeToInclusive<usize>
)
Deref::deref
AsRef::<[T]>::as_ref
您应该实施哪些?我不知道;哪些有意义?阅读有关每种方法(和相关特征)的文档,看看它描述的内容是否是您想要允许的。你说 "that can retrieve a slice",但你并没有真正解释那是什么意思。 traits 的很大一部分不仅仅是抽象出通用接口,而是赋予这些接口超出代码严格允许的含义。
如果列出的方法不对;如果其中 none 个 相当 表达了正确的语义,则创建一个新特征。不要仅仅因为技术上 可以 .
就被迫实施特征
至于 Into
,同样,阅读文档:
A conversion that consumes self
, which may or may not be expensive.
强调我的。在这种情况下实现 Into
是没有意义的:如果您使用该值,则无法从中借用。哦,还有:
Library authors should not directly implement this trait, but should prefer implementing the From
trait, which offers greater flexibility and provides an equivalent Into
implementation for free, thanks to a blanket implementation in the standard library.
所以是的,我不会为此使用 Into
。或者 From
.
我正在研究 a library that operates on [T]
slices。我希望库用户指定一种可以以可变或不可变方式检索切片的类型。
我当前的库定义了 2 个特征
pub trait SliceWrapper<T> {
fn slice(&self) -> &[T];
}
pub trait SliceWrapperMut<T> {
fn slice_mut (&mut self) -> &mut [T];
}
但是名称 slice
和 slice_mut
似乎是任意的,而不是核心 Rust 库中的某个地方。
有没有我应该要求的特质,比如 Into::<&mut [T]>
?
我担心 Into
会使用该类型而不仅仅是引用它,所以我不能简单地要求调用者类型实现 core::convert::Into
,可以吗?
回答这个问题的最简单方法是查看现有类型的文档,这些类型或多或少可以满足您的需求。这听起来像是 Vec
会做的,那么为什么不看看 documentation for Vec
?
如果您在其中搜索 -> &
,您会发现许多 return 借用切片的方法:
Vec::as_slice
Borrow::borrow
Index::<Range<usize>>::index
(加上RangeTo<usize>
、RangeFrom<usize>
、RangeFull
、RangeInclusive<usize>
和RangeToInclusive<usize>
)Deref::deref
AsRef::<[T]>::as_ref
您应该实施哪些?我不知道;哪些有意义?阅读有关每种方法(和相关特征)的文档,看看它描述的内容是否是您想要允许的。你说 "that can retrieve a slice",但你并没有真正解释那是什么意思。 traits 的很大一部分不仅仅是抽象出通用接口,而是赋予这些接口超出代码严格允许的含义。
如果列出的方法不对;如果其中 none 个 相当 表达了正确的语义,则创建一个新特征。不要仅仅因为技术上 可以 .
就被迫实施特征至于 Into
,同样,阅读文档:
A conversion that consumes
self
, which may or may not be expensive.
强调我的。在这种情况下实现 Into
是没有意义的:如果您使用该值,则无法从中借用。哦,还有:
Library authors should not directly implement this trait, but should prefer implementing the
From
trait, which offers greater flexibility and provides an equivalentInto
implementation for free, thanks to a blanket implementation in the standard library.
所以是的,我不会为此使用 Into
。或者 From
.