extern crate serde; extern crate serde_json; #[macro_use] extern crate serde_derive; #[derive(Serialize)] pub struct MyStruct<'a> { pub field1: &'a str, pub field2: &'a str, } pub trait MyTrait { fn payload_to_json(&self) -> String { serde_json::to_string(&self) } fn do_the_thing(&self) { println!(payload_to_json(&self)); } } impl MyTrait for MyStruct<'_> {} fn main() { let n = MyStruct { field1: "foo" field2: "bar" } n.do_the_thing(); } // What I'm hoping for: { "field1": "foo", "field2": "bar" } This gives me the following error:
error[E0277]: the trait bound `Self: Serialize` is not satisfied --> src/main.rs:10:31 | 10 | serde_json::to_string(&self) | ^^^^^ the trait `Serialize` is not implemented for `Self` I'm new to Rust so probably missing something easy; the only struct implementing MyTrait does have Serialize implemented (unless I'm misunderstanding what derive() does), so I presume there's something that the compiler's not being told about .. somewhere. Can anybody help?