gpt4 book ai didi

json - impl 不引用此 crate 中定义的任何类型

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

在我的一个结构 Struct1 中,有一个类型为 time::Tm 的字段。在代码的某处,结构的实例从 json 字符串解码为 Struct1 的实例。

json::decode(&maybe_struct1)

一开始我得到一个错误,说 to_json 没有为 time::Tm 实现。所以我实现了它:

impl json::ToJson for time::Tm {
fn to_json(&self) -> json::Json {
let mut d = BTreeMap::new();
d.insert("tm_sec".to_string(), self.tm_sec.to_json());
d.insert("tm_min".to_string(), self.tm_min.to_json());
//..............

现在它说

error: the impl does not reference any types defined in this crate; only traits defined in the current crate can be implemented for arbitrary types  [E0117]

我猜想这是版本 1 之前的错误。但它仍然是?如果不是,我该如何解决?

最佳答案

这不是错误 - 这是功能。真的。要实现特征,以下任何语句都必须为真:

  • 类型在这个模块中声明
  • trait 在这个模块中声明

否则你会得到 E0117。您可以使用 rustc --explain E0117 找到更多信息:

This error indicates a violation of one of Rust's orphan rules for trait implementations. The rule prohibits any implementation of a foreign trait (atrait defined in another crate) where

  • the type that is implementing the trait is foreign
  • all of the parameters being passed to the trait (if there are any) are also foreign.

Here's one example of this error:

impl Drop for u32 {}

To avoid this kind of error, ensure that at least one local type is referencedby the impl:

pub struct Foo; // you define your type in your crate

impl Drop for Foo { // and you can implement the trait on it!
// code of trait implementation here
}

impl From<Foo> for i32 { // or you use a type from your crate as
// a type parameter
fn from(i: Foo) -> i32 { 0 }
}

Alternatively, define a trait locally and implement that instead:

trait Bar {
fn get(&self) -> usize;
}
impl Bar for u32 {
fn get(&self) -> usize { 0 }
}

For information on the design of the orphan rules, see RFC 1023.

编辑:

要实现你想要的,你有 2 个解决方案:

  • 在您的整个类型上实现 ToJson:

     impl json::ToJson for Struct1 { … }
  • 创建一个包装器类型 struct TmWrapper(time::Tm); 并为其实现 2 个特征 FromToJson

编辑 2:

逐步展开:

  1. 这是您想要实现的目标:http://is.gd/6UF3jd
  2. 解决方案:

正是上面错误代码的解释中描述的内容。

所以您看 - 至少必须在当前单元中声明 trait 或 struct 之一,以允许在给定类型上实现 trait。在您的情况下,它们都是外部类型,这就是 Rust 所防止的。如果你想实现类似的目标,你需要使用上面描述的一些技巧。

关于json - impl 不引用此 crate 中定义的任何类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32034529/

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