I'm new in Rust and I'm working on simple CLI program, so I have a problem. The problem is I create a new object every single time when I run a program but I want to load from JSON. I don't know how to implement it because another part of my code using this object to manipulate with others things in program.
This is the part of my main file:
fn main() { let mut new_user = Profile::new(); loop { println!("=== MENU ==="); println!("1 - show profile"); println!("2 - add hours"); println!("3 - decrease hours"); println!("4 - show all leagues"); println!("5 - exit"); let user_choice = read_user_input("Enter your choice (1 - 5): "); match user_choice { 1 => new_user.show_profile(), 2 => new_user.increase_hours_change_league(), 3 => new_user.decrease_hours_change_league(), 4 => show_leagues(), 5 => break, _ => println!("Invalid input! Try again!"), } } if let Err(e) = save_profile(&new_user) { println!("Error! {}", e); }; } This is the part of my file with Profile struct:
use crate::user_io::read_user_hours; use serde::{Deserialize, Serialize}; #[derive(Deserialize, Serialize, Debug)] pub struct Profile { hours: i32, league: String, } impl Profile { pub fn new() -> Self { Profile { hours: 0, league: String::from("Bronze I"), } } pub fn show_profile(&self) { println!("=== PROFILE ==="); println!("League: {}", self.league); println!("Hours: {}", self.hours); } pub fn check_hours_change_league(&mut self) { match self.hours { _ if self.hours >= 0 && self.hours < 25 => self.league = String::from("Bronze I"), _ if self.hours >= 25 && self.hours < 50 => self.league = String::from("Bronze II"), _ if self.hours >= 50 && self.hours < 100 => self.league = String::from("Bronze III"), _ => println!("Something went wrong..."), } } pub fn increase_hours_change_league(&mut self) { let hours = read_user_hours("Enter hour(s) you want to add"); self.hours += hours; self.check_hours_change_league(); } pub fn decrease_hours_change_league(&mut self) { let hours = read_user_hours("Enter hour(s) you want to decrease"); self.hours -= hours; self.check_hours_change_league(); } } P.S. Thank you everyone for your time and advise!
2 posts - 2 participants