gpt4 book ai didi

rust - 是否可以检查字段是否实现了具有自定义派生的特征?

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

struct Foo;

#[derive(Clone)]
struct Bar {
f: Foo,
}

fn main() {}

Playground

这导致

error[E0277]: the trait bound `Foo: std::clone::Clone` is not satisfied
--> <anon>:5:5
|
5 | f: Foo,
| ^^^^^^ the trait `std::clone::Clone` is not implemented for `Foo`
|
= note: required by `std::clone::Clone::clone`

只有所有类型的字段都实现了克隆,才有可能派生出克隆。我也想做同样的事情。

Field似乎没有暴露它实现了哪些特征。我如何检查 Type实现特定特征?这目前不可能吗?

最佳答案

看看 expanded version你的代码:

#![feature(prelude_import)]
#![no_std]
#[prelude_import]
use std::prelude::v1::*;
#[macro_use]
extern crate std as std;
struct Foo;

struct Bar {
f: Foo,
}
#[automatically_derived]
#[allow(unused_qualifications)]
impl ::std::clone::Clone for Bar {
#[inline]
fn clone(&self) -> Bar {
match *self {
Bar { f: ref __self_0_0 } => Bar { f: ::std::clone::Clone::clone(&(*__self_0_0)) },
}
}
}

fn main() {}

它所做的只是调用一个具有特征绑定(bind)的函数,并传入参数。这很有用,因为无论如何都需要递归调用 clone。这让您“免费”获得支票。

如果您不需要调用有问题的特征,您仍然可以执行类似于 enforce that an argument implements a trait at compile time 的操作. Eq 通过实现 hidden function on the trait 来做到这一点.您还可以生成一次性函数来表达您的特征界限。

关于rust - 是否可以检查字段是否实现了具有自定义派生的特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42873092/

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