Generics 实施从和进入
我想将“A”的类型转换为“B”,将“A”的集合转换为“B”的集合(反之亦然) 我对这个机制的工作原理有些误解 我假设在基类型上实现Generics 实施从和进入,generics,rust,traits,Generics,Rust,Traits,我想将“A”的类型转换为“B”,将“A”的集合转换为“B”的集合(反之亦然) 我对这个机制的工作原理有些误解 我假设在基类型上实现From将类似地转移到集合,而不显式实现 例如: 结构A{ 文本:字符串 } 结构B{ 文本:字符串 } 为B从impl开始{ fn来自(a:a)->Self{ B{text:a.text} } } fn main(){ 设a=a{text:“hello.”to_string()}; 设b=b::from(a);//有效 设a2=A{text:“hello.”to_
From
将类似地转移到集合,而不显式实现
例如:
结构A{
文本:字符串
}
结构B{
文本:字符串
}
为B从impl开始{
fn来自(a:a)->Self{
B{text:a.text}
}
}
fn main(){
设a=a{text:“hello.”to_string()};
设b=b::from(a);//有效
设a2=A{text:“hello.”to_string()};
让b2=a.into();//起作用
让v1=vec![A{text:“hello”.to_string()}];
设v2=Vec:::from(v1);//不起作用
让v2:Vec=v1.into();//不起作用
}
转换集合时出现的错误:
Compiling playground v0.0.1 (/playground)
error[E0277]: the trait bound `Vec<B>: From<Vec<A>>` is not satisfied
--> src/main.rs:20:14
|
20 | let v2 = Vec::<B>::from(v1); // doesn't work
| ^^^^^^^^^^^^^^ the trait `From<Vec<A>>` is not implemented for `Vec<B>`
|
= help: the following implementations were found:
<Vec<T, A> as From<Box<[T], A>>>
<Vec<T> as From<&[T]>>
<Vec<T> as From<&mut [T]>>
<Vec<T> as From<BinaryHeap<T>>>
and 6 others
= note: required by `from`
error[E0277]: the trait bound `Vec<B>: From<Vec<A>>` is not satisfied
--> src/main.rs:21:26
|
21 | let v2 : Vec<B> = v1.into(); // doesn't work
| ^^^^ the trait `From<Vec<A>>` is not implemented for `Vec<B>`
|
= help: the following implementations were found:
<Vec<T, A> as From<Box<[T], A>>>
<Vec<T> as From<&[T]>>
<Vec<T> as From<&mut [T]>>
<Vec<T> as From<BinaryHeap<T>>>
and 6 others
= note: required because of the requirements on the impl of `Into<Vec<B>>` for `Vec<A>`
编译操场v0.0.1(/playerd)
错误[E0277]:未满足特征绑定'Vec:From'
-->src/main.rs:20:14
|
20 |设v2=Vec::from(v1);//不起作用
|^^^^^^^^^^^^^^^^^^^^^^^^未为`Vec实现特性`From``
|
=帮助:找到了以下实现:
和其他6人
=注:由`from'要求`
错误[E0277]:未满足特征绑定'Vec:From'
-->src/main.rs:21:26
|
21 |让v2:Vec=v1.into();//不起作用
|^^^^未为`Vec'实现特性`From``
|
=帮助:找到了以下实现:
和其他6人
=注:由于“Vec”的“Into”impl要求,因此需要`
这些嵌套转换是否有“一揽子”实现?如果没有,那么实现这种灵活性的最佳方法是什么?在将项目收集到新的向量之前,使用vec和map:
让v2:Vec=v1.into_iter().map(into::into.collect();
如果你想找一个与你所提供的语法相似的语法,你可能需要考虑编写你自己的通用特性,<代码> FromVec < /C> >,例如:
trait FromVec<T> {
fn from_vec(val: Vec<T>) -> Self;
}
impl<T, S: From<T>> FromVec<T> for Vec<S> {
fn from_vec(val: Vec<T>) -> Self {
val.into_iter().map(Into::into).collect()
}
}
并为其提供全面实施:
impl<T, S> IntoVec<T> for Vec<S>
where Vec<T>: FromVec<S>
{
fn into_vec(self) -> Vec<T> {
Vec::from_vec(self)
}
}
为什么这不是标准库的一部分:)?
trait IntoVec<T> {
fn into_vec(self) -> Vec<T>;
}
impl<T, S> IntoVec<T> for Vec<S>
where Vec<T>: FromVec<S>
{
fn into_vec(self) -> Vec<T> {
Vec::from_vec(self)
}
}
fn main() {
let vec_a = vec![A { text: "hello".to_string() } ];
let vec_b = Vec::<B>::from_vec(vec_a);
let vec_a = vec![A { text: "hello".to_string() } ];
let vec_b: Vec<B> = vec_a.into_vec();
}