Overview
在本指南中,您可以学习;了解边界以及如何解决常见的边界错误。
什么是边界?
特征边界允许方法限制它们接受作为参数的类型以及这些类型必须实现的功能。示例,如果您定义一个接受泛型类型参数并打印其值的方法,则该参数必须实现Display 特征才能打印。以下示例定义了 printer() 方法并指定其参数必须实现Display:
fn printer<T: Display>(t: T) { println!("{}", t); }
常见边界错误
在数据类型上调用方法时,可能会遇到错误,指出不满足该方法的特征边界。 例如,当您对Cursor实例调用try_next()方法时,驱动程序可能会引发以下错误消息:
error[E0599]: the method `try_next` exists for struct `mongodb::Cursor<T>`, but its trait bounds were not satisfied
如果满足 的特征边界,则 Cursor<T>类型仅实现访问权限 方法所需的Streamtry_next()T 特征。也就是说,T 必须实现DeserializeOwned 游标 API文档中指定的 特征。以下示例通过定义对Actor actors集合中的文档进行建模的自定义 结构体来重现上述错误消息。但是,此结构体未实现DeserializeOwned Actor特征,使用try_next() 方法遍历 会导致错误:
// This code example produces a trait bounds error because // the Actor struct does not implement the DeserializeOwned trait. struct Actor { name: String, } // Add setup code here let my_coll: Collection<Actor> = client.database("db").collection("actors"); let mut cursor = my_coll.find(doc! {}).await?; while let Some(result) = cursor.try_next().await? { println!("{:?}", result); };
要解决特征边界错误,请确定游标迭代的数据类型,并确保该数据类型实现DeserializeOwned特征。 您可以使用derive属性来应用所需的特征边界。
注意
Deserialize 和 DeserializeOwned 特征
serde包提供派生宏来生成某些特征的实现,包括Deserialize特征。 但是,此板条箱不提供DeserializeOwned特征的派生宏。 实现Deserialize而没有生命周期限制的数据类型会自动实现DeserializeOwned ,因此您可以实现Deserialize来满足DeserializeOwned特征边界。
以下示例调整Actor结构体定义以实施Deserialize :
struct Actor { name: String, }
其他资源
有关特征边界的更多信息,请参阅以下资源: