Last active
October 31, 2022 11:25
-
-
Save se1983/78c0c5e4ed0ce43a1ef704408999ec18 to your computer and use it in GitHub Desktop.
rust constructors creating structs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use serde::{Deserialize, Serialize}; | |
pub trait SerdeDeserializeObject { | |
fn new<'de>(data: &'de str) -> Self | |
where | |
Self: Deserialize<'de>, | |
{ | |
let serialized_data: Self = serde_json::from_str(&data).unwrap(); | |
serialized_data | |
} | |
} | |
#[derive(Debug, Serialize, Deserialize)] | |
pub struct Test { | |
pub x: String, | |
} | |
impl SerdeDeserializeObject for Test {} | |
fn main() { | |
// Creating json object for testing {"x": "Hello World"} | |
let test = Test{x: String::from("Hello World")}; | |
let serialized = serde_json::to_string(&test).unwrap(); | |
// Creating an instance of Test using the constructor from SerdeDeserializeObject | |
let deserialized_data = Test::new(&serialized); | |
assert!(deserialized_data.x == "Hello World"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait Object { | |
fn new() -> Self; | |
} | |
struct Data { | |
x: String | |
} | |
impl Object for Data { | |
fn new() -> Data { | |
Self {x: String::from("Hello World")} | |
} | |
} | |
fn main() { | |
println!("{}", Data::new().x); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment