如何将 Debug 与特征对象一起使用?

问题描述 投票:0回答:1

我想在

Debug
结构上实现
Post
特征,该结构有一个特征对象作为值,但我从下面得到堆栈溢出错误:

thread 'main' has overflowed its stack
fatal runtime error: stack overflow
use std::fmt::{Debug, Display, Formatter, Result as fmtResult};

#[derive(Debug)]
pub struct Post {
    state: Option<Box<dyn State>>,
    content: String,
}

trait State {
    fn request_review(self: Box<Self>) -> Box<dyn State>;
    fn approve(self: Box<Self>) -> Box<dyn State>;
    fn content<'a>(&self, post: &'a Post) -> &'a str {
        ""
    }
}

impl Debug for dyn State {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmtResult {
        write!(f, "{}", self)
    }
}

impl Display for dyn State {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmtResult {
        write!(f, "{}", self)
    }
}
debugging rust traits
1个回答
2
投票

如果你想要任何东西实现

State
也实现
Debug
,那么你可以这样做:

trait State: Debug {
        // ^^^^^^^
    fn request_review(self: Box<Self>) -> Box<dyn State>;
    fn approve(self: Box<Self>) -> Box<dyn State>;
    ...
}

然后

#[derive(Debug)]
将在
Post
上运行,无需任何手动实现。 游乐场上的完整代码

© www.soinside.com 2019 - 2024. All rights reserved.