gpt4 book ai didi

rust - 将 Option 转换为 Option>

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

是否可以映射 Option<impl Trait>Option<Box<dyn Trait>> ?如果参数为 new()不是 Option ,可以将其分配给 structSome(Box::new(item)) .为什么这行得通,而 map 却行不通?

trait TestTrait {}

impl TestTrait for i32 {}

struct TestStruct {
item: Option<Box<dyn TestTrait>>
}

impl TestStruct {
pub fn new(item: Option<impl TestTrait + 'static>) -> Self {
let item: Option<Box<dyn TestTrait>> = item.map(|i| Box::new(i));
Self {
item
}
}
}


fn main() {
let num:i32 = 0;
let s = TestStruct::new(Some(num));
}

最佳答案

看起来编译器无法推断闭包的正确类型。如果您明确指定它,则一切正常( playground ):

trait TestTrait {}

impl TestTrait for i32 {}

struct TestStruct {
item: Option<Box<dyn TestTrait>>
}

impl TestStruct {
pub fn new(item: Option<impl TestTrait + 'static>) -> Self {
let item = item.map(
|i| -> Box<dyn TestTrait> {
Box::new(i)
}
);
Self {
item
}
}
}

fn main() {
let num:i32 = 0;
let _ = TestStruct::new(Some(num));
}

关于rust - 将 Option<impl Trait> 转换为 Option<Box<dyn Trait>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65604092/

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