gpt4 book ai didi

rust - 如何编写一个未实现的函数来返回没有伪代码的 impl Trait?

转载 作者:行者123 更新时间:2023-11-29 08:00:19 25 4
gpt4 key购买 nike

我试过这个:

trait T {}

fn f() -> impl T {
unimplemented!();
}

fn main() {
f();
}

但它给出了这个错误:

error[E0277]: the trait bound `!: T` is not satisfied
--> src/main.rs:3:11
|
3 | fn f() -> impl T {
| ^^^^^^ the trait `T` is not implemented for `!`
|
= note: the return type of a function must have a statically known size

如果 f 中的分支返回某些内容,则编译:

struct S {}

trait T {}

impl T for S {}

fn f(a: u32) -> impl T {
if a == 0 {
panic!();
} else {
S {}
}
}

fn main() {
f(5);
}

最佳答案

这是一个 known issue .

简单(作弊)的答案是为 实现你的特征!:

impl T for ! {}

你可以在tracking issue for promoting ! to a type中看到很多讨论都围绕着为一个类型实现哪些特征。

还有 an RFC to implement traits automatically for ! ,但没有被接受。这需要“实现”特征中的任何方法,因为 another proposed RFC也被推迟了:

trait T {
fn hello(&self) -> u32;
}

impl T for ! {
fn hello(&self) -> u32 {
*self
}
}

关于rust - 如何编写一个未实现的函数来返回没有伪代码的 impl Trait?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49600368/

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