Is there a way to signal that an impl trait type also implements additional traits?

可紊 提交于 2021-02-10 17:45:07

问题


I have a function that returns an impl trait:

pub fn new(buf: &[u8]) -> Result<impl Temperature, u8>

Is there a way to signal that the underlying struct also implements Debug (via #[derive(...)]), so I can format the value?


回答1:


Yes, combine multiple traits with a +, just like in trait bounds:

use std::fmt::Debug;

trait Foo {}

fn new() -> impl Foo + Debug {
    Dummy
}

#[derive(Debug)]
struct Dummy;
impl Foo for Dummy {}

fn main() {
    println!("{:?}", new());
}


来源:https://stackoverflow.com/questions/49263023/is-there-a-way-to-signal-that-an-impl-trait-type-also-implements-additional-trai

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!