Home > Blockchain >  How to create object in Rust like in Java?
How to create object in Rust like in Java?

Time:08-31

I'm new to Rust, and I would like to know if it's possible to create serializable objects like we do in Java. For instance, my Java class looks like this:

public class Obj implements Serializable {
    int objNo;
    String objName;
    
    public Obj (int objNo, String objName) {
        this.objNo = sushiNo;
        this.objName = objName;
    }
}

I am able to create and access the object in another function, like below:

Obj obj1 = new Obj(objNo, objName);
System.out.println("Object"   objNo   ": "   objName);

How do I translate this serializable/deserializable Java object into Rust and be able to access it? If it is not possible to create something like this, are there any alternatives?

I've read about struct and Serde, but I don't know how to implement it because the syntax looks very confusing to me, which is why I'm asking for help.

CodePudding user response:

In case it helps, here is a trivial example which serialises some structs to a json string then deserialises this json string in order to recreate the equivalent structs. But if you are not familiar with the basic elements of the Rust language, this will not be very helpful.

use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct Stat {
    name: String,
    values: Vec<f32>,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let prepared_stats = vec![
        Stat {
            name: "age".to_owned(),
            values: vec![37.0, 51.0, 46.0, 28.0],
        },
        Stat {
            name: "BMI".to_owned(),
            values: vec![28.2, 21.3, 18.4, 20.4],
        },
    ];
    println!("prepared_stats:\n  {:?}", prepared_stats);
    let json_serialised_stats = serde_json::to_string(&prepared_stats)?;
    println!("json_serialised_stats:\n  {}", json_serialised_stats);
    let deserialised_stats =
        serde_json::from_str::<Vec<Stat>>(&json_serialised_stats)?;
    println!("deserialised_stats:\n  {:?}", deserialised_stats);
    Ok(())
}
/*
prepared_stats:
  [Stat { name: "age", values: [37.0, 51.0, 46.0, 28.0] }, Stat { name: "BMI", values: [28.2, 21.3, 18.4, 20.4] }]
json_serialised_stats:
  [{"name":"age","values":[37.0,51.0,46.0,28.0]},{"name":"BMI","values":[28.2,21.3,18.4,20.4]}]
deserialised_stats:
  [Stat { name: "age", values: [37.0, 51.0, 46.0, 28.0] }, Stat { name: "BMI", values: [28.2, 21.3, 18.4, 20.4] }]
*/

In Cargo.toml

[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
  • Related