【问题标题】:Debug trait not implemented for some enum variants某些枚举变体未实现调试特征
【发布时间】:2019-05-24 10:52:38
【问题描述】:

我有这个枚举:

#[derive(Debug)]
pub enum TokenType {
    Illegal,
    Integer(String),
    Ident(String),
}

fn main() {
    let vals = vec![(TokenType::Ident, "identifier")];
    println!("Expected one of {:?}", vals);
}

Playground

当我尝试使用 TokenType 值时,它似乎忽略了 Debug 派生,并且我收到以下编译器错误:

error[E0277]: `fn(std::string::String) -> TokenType {TokenType::Ident}` doesn't implement `std::fmt::Debug`
  --> src/main.rs:10:38
   |
10 |     println!("Expected one of {:?}", vals);
   |                                      ^^^^ `fn(std::string::String) -> TokenType {TokenType::Ident}` cannot be formatted using `{:?}` because it doesn't implement `std::fmt::Debug`
   |
   = help: the trait `std::fmt::Debug` is not implemented for `fn(std::string::String) -> TokenType {TokenType::Ident}`
   = note: required because of the requirements on the impl of `std::fmt::Debug` for `(fn(std::string::String) -> TokenType {TokenType::Ident}, &str)`
   = note: required because of the requirements on the impl of `std::fmt::Debug` for `std::vec::Vec<(fn(std::string::String) -> TokenType {TokenType::Ident}, &str)>`
   = note: required by `std::fmt::Debug::fmt`

在我看来,这个问题是因为我有一些包含 String 的枚举变体(例如 Ident(String))它没有正确派生 Debug 特征,但我不知道如何解决。

是否有某种方法可以强制 Rust 为该枚举派生特征,或者有没有一种方法可以通过为这些变体手动实现 fmt::Debug 来解决此错误?

【问题讨论】:

  • 这个vals 向量是什么意思?你想输出什么?

标签: rust


【解决方案1】:

TokenType::Ident不是枚举变体;它是一个枚举变体构造函数。错误信息指出它是一个函数:

fn(std::string::String) -> TokenType {TokenType::Ident}

函数没有实现Debug。没有你想要的解决方案。

【讨论】:

  • 有趣,我不知道那些被认为是函数,但我想这是有道理的。所以没有办法在这样的枚举上实现Debug,即使是手动的?
  • @RPiAwesomeness Debug 是针对枚举值实现的;你没有枚举值。
猜你喜欢
  • 1970-01-01
  • 2019-11-25
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 2022-12-31
  • 2021-10-31
相关资源
最近更新 更多