gpt4 book ai didi

rust - 使用 None 实例化时不指定 T 的情况下使用 Option 创建通用结构

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

我有一个

struct Foo<T>
where
T: // ... some complex trait bound ...
{
a: Bar,
b: Option<T>,
}

尝试用 b: None 实例化结构时编译器提示它无法推断类型并需要类型提示,例如通过 turbofish 语法。这对调用者来说是繁重的,因为他们将不得不找到一个满足特征界限的类型并导入它,尽管他们不关心那个可选功能。

我想我正在寻找的是一个底部类型,它会自动满足任何特征边界但不能被实例化,所以 None::<Bottom>可以使用,但我没有在文档中找到这样的类型。

最佳答案

a feature in the works这允许将 never type 指定为 !。这在稳定的 Rust 中不存在,因此您需要使用 nightly 和功能标志:

#![feature(never_type)]

fn thing<T>() -> Option<T> {
None
}

fn main() {
thing::<!>();
}

但是,这还不适用于您的情况(这是它不稳定的部分原因):

#![feature(never_type)]

trait NothingImplementsMe {}

fn thing<T>() -> Option<T>
where T: NothingImplementsMe,
{
None
}

fn main() {
thing::<!>();
}
error[E0277]: the trait bound `!: NothingImplementsMe` is not satisfied
--> src/main.rs:12:5
|
12 | thing::<!>();
| ^^^^^^^^^^ the trait `NothingImplementsMe` is not implemented for `!`
|
= note: required by `thing`

关于跟踪问题的第一个 Unresolved 问题是:

What traits should we implement for !?


由于此功能既不稳定又不能满足您的要求,您可能需要考虑创建自己的定制“底部”类型:

trait AlmostNothingImplementsMe {
fn foo();
}

struct Nope;
impl AlmostNothingImplementsMe for Nope {
fn foo() { unimplemented!() }
}

fn thing<T>() -> Option<T>
where T: AlmostNothingImplementsMe,
{
None
}

fn main() {
thing::<Nope>();
}

为了改进它的用户体验,我建议创建某种类型的构建器,让您从人造底部类型开始:

mod nested {
pub trait AlmostNothingImplementsMe {
fn foo();
}

pub struct Nope;
impl AlmostNothingImplementsMe for Nope {
fn foo() { unimplemented!() }
}

pub fn with_value<T>(t: T) -> Option<T>
where T: AlmostNothingImplementsMe,
{
Some(t)
}

pub fn without_value() -> Option<Nope> {
None
}
}

fn main() {
nested::without_value();
}

您可以看到类似的模式 in crates like Hyper ,虽然它包含具体类型,因此您从外面看不到它。

关于rust - 使用 None 实例化时不指定 T 的情况下使用 Option<T> 创建通用结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42141129/

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