Skip to content

Instantly share code, notes, and snippets.

@se1983
Last active October 31, 2022 11:25
Show Gist options
  • Save se1983/78c0c5e4ed0ce43a1ef704408999ec18 to your computer and use it in GitHub Desktop.
Save se1983/78c0c5e4ed0ce43a1ef704408999ec18 to your computer and use it in GitHub Desktop.
rust constructors creating structs
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");
}
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