0
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?

1 Answer 1

1

Bind your trait to Serialize:

pub trait MyTrait: Serialize { fn payload_to_json(&self) -> String { serde_json::to_string(&self).expect("A valid json") } fn do_the_thing(&self) { println!("{}", self.payload_to_json()); } } 

Playground

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.