gpt4 book ai didi

collections - 如果元素可以转换,为什么不能使用 .into() 转换容器?

转载 作者:行者123 更新时间:2023-12-03 11:25:33 25 4
gpt4 key购买 nike

如果我有一个 Vec<T>我无法将其转换为 Vec<U>直接使用 .into()即使我可以转换 T进入U使用 .into() .例如,这段代码无法编译:

use std::convert::From;

struct A {
x: i32,
}

struct B {
y: u64,
}

impl From<A> for B {
fn from(a: A) -> Self {
Self {
y: a.x as u64,
}
}
}

fn main() {
let avec: Vec<A> = vec![A{x: 1}, A{x: 2}];
let bvec: Vec<B> = avec.into(); // Error!
}

我觉得应该可以有这样的毯子:

impl<T, U> From<Vec<T>> for Vec<U> where T: From<U> {
fn from(t: Vec<T>) -> Self {
t.into_iter().map(Into::into).collect()
}
}

其他系列也是如此。有没有这样做的原因?当你想转换时,它会节省很多繁琐的代码,比如 HashMap<String, Vec<Vec<u32>>>HashMap<String, Vec<Vec<u64>>> .

最佳答案

(当前)对转换容器进行一揽子实现的问题是,它与现有的一揽子实现相冲突 impl From<T> for T .

为了能够解决这个问题,简而言之需要 specialization (Issue #31844)。

// This:
impl<T, U> From<Vec<T>> for Vec<U> where T: From<U>

// Would conflicts with this:
impl<T> From<T> for T

不久前在Rust论坛上讨论过同样的问题:

关于collections - 如果元素可以转换,为什么不能使用 .into() 转换容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66350655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com