gpt4 book ai didi

rust - 如何为盒装值指定 `Sized`

转载 作者:行者123 更新时间:2023-11-29 08:06:16 24 4
gpt4 key购买 nike

我想通知“此方法将返回实现 TraitSized 的盒装 Struct”。简单的解决方案就是将 Struct 放入 Box 但我不能,因为 Struct 有太大的通用参数,我无法手动编写。

// I can't edit these trait and struct.
trait Trait {}
struct Struct();
impl Trait for Struct {}

// This is my code.
fn func() -> Box<Trait> {
Box::new(Struct{})
}

// This is not my code.
fn need_sized<T: Trait + Sized>(item: T) {
println!("ok");
}

fn main() {
// This can not be compiled!
need_sized(func());
}

我可以编辑 func 函数,但不能编辑其他函数。

如何指定 Trait 实现 Sized?是不是像下面这样的东西?

fn func() -> Box<Trait + Sized>

最佳答案

鉴于规范,您可以绕过它的唯一方法是制作 newtype wrapper .

// I can't edit these trait and struct.
trait Trait {}
struct Struct();
impl Trait for Struct {}


// This is my code.
struct MyStruct(Struct);
impl Trait for Box<MyStruct> { /* if there is code here delegate to inner `Struct` */}

fn func() -> Box<MyStruct> {
Box::new(MyStruct(Struct{}))
}

// This is not my code.
fn need_sized<T: Trait + Sized>(item: T) {
println!("ok");
}

fn main() {
// This can not be compiled!
need_sized(func());
}

playground

为什么其他方法不能解决您的问题:

  1. 单态性状

    fn func<T: Trait>() -> Box<T> { ... }

您想通过funcneed_size .更具体地说,您想传递 Boxneed_size功能。

  1. 将函数签名更改为 Box<Struct>

error[E0277]: the trait bound std::boxed::Box<Struct>: Trait is not satisfied

--> <anon>:22:5
  |
22| need_sized(func());
| ^^^^^^^^^^ the trait `Trait` is not implemented for `std::boxed::Box<Struct>`
|= help: the following implementations were found:
<std::boxed::Box<MyStruct> as Trait>
= note: required by `need_sized`

这行不通,因为您无法控制 BoxStruct因为它们没有在你的 crate 中定义,所以它会扰乱一致性规则。将来这可能会使用特殊的一致性规则来解决。

关于rust - 如何为盒装值指定 `Sized`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43913009/

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