我想实现这个Shl特性Vec,代码如下.这会使事情变得vec << 4可能,这对于它来说是个不错的选择vec.push(4).
use std::ops::Shl;
impl<T> Shl<T> for Vec<T> {
type Output = Vec<T>;
fn shl(&self, elem: &T) -> Vec<T> {
self.push(*elem);
*self
}
}
fn main() {
let v = vec![1, 2, 3];
v << 4;
}
Run Code Online (Sandbox Code Playgroud)
编译失败,出现以下错误:
无法提供扩展实现,其中特征和类型都未在此包中定义[E0117]
要么
type参数
T必须用作某些本地类型的类型参数(例如MyStruct<T>); 只有当前包中定义的特征才能为类型参数实现[E0210]
据我了解,我必须修补stdlib,更具体地来说是collections::vec板条箱.有没有其他方法可以更改此代码以成功编译?
我有一个设计问题,当使用类似的东西时:
trait MyTrait<K: OtherTrait> { ... }
impl<K: OtherTrait, M: MyTrait<K>> AnyTrait for M { ... }
Run Code Online (Sandbox Code Playgroud)
由于E207错误("类型参数K不受impl trait,self type或谓词"约束),我无法为此特征实现特征.
找不到摆脱这个错误,我应用这个不那么好看的解决方法(详细和结构没有内在价值):
use std::fmt;
use std::marker::PhantomData;
pub trait MyTrait<K: fmt::Display> {
fn get_some_k(&self) -> Option<K>;
}
/* // This is my target impl but results in E207 due to K not constrained
impl<K: fmt::Display, S: MyTrait<K>> fmt::Display for S {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.get_some_k().unwrap())
}
} */
pub struct Ugly<'a, …Run Code Online (Sandbox Code Playgroud) 为什么代码示例1编译但示例2给出了编译错误?
例1:
use std::ops::Index;
struct Bounded {
idx: usize,
}
impl Index<Bounded> for [i32; 4] {
type Output = i32;
fn index(&self, b: Bounded) -> &i32 {
unsafe { self.get_unchecked(b.idx) }
}
}
Run Code Online (Sandbox Code Playgroud)
例2:
use std::ops::Index;
struct Bounded {
idx: usize,
}
impl<T> Index<Bounded> for [T; 4] {
type Output = T;
fn index(&self, b: Bounded) -> &T {
unsafe { self.get_unchecked(b.idx) }
}
}
Run Code Online (Sandbox Code Playgroud)
error[E0210]: type parameter `T` must be used as the type parameter for some local type …Run Code Online (Sandbox Code Playgroud)