Trying to Pass Value To Struct From Console Not Static


#1
use std::io;
use std::fmt;

struct Length(i32);

impl fmt::LowerHex for Length {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let val = self.0;

        write!(f, "{:x}", val) // delegate to i32's implementation
    }
}  

fn main() {    
    let mut input_text = String::new();
    io::stdin()
        .read_line(&mut input_text)
        .expect("failed to read from stdin");

    let trimmed = input_text.trim();
       
    match trimmed.parse::<i32>() {
        Ok(i) => println!("your integer input: {}", i),
        Err(..) => println!("this was not an integer: {}", trimmed)}
   
/// need to pass i32 value to Length (currently static value "21"
      
        let l = Length(21);
        println!("l as hex is: {:x}", l);
        
        
    }

#2

I think I understand what you are trying to do, but more info would be welcome. You can either return the parsed integer from the match expression, like this:

let length = match trimmed.parse::<i32>() {
    Ok(i) => i,
    Err(_) => {
        println!("this was not an integer: {}", trimmed);
        0 //default to 0 in this example
    }
};

let l = Length(length);
println!("l as hex is: {:x}", l);

or do the final operations within the match arm, like this:

match trimmed.parse::<i32>() {
    Ok(i) => {
        let l = Length(i);
        println!("l as hex is: {:x}", l);
    },
    Err(_) => println!("this was not an integer: {}", trimmed),
}

It depends on what you are trying to do. Also, an additional piece of advice; surround your code with three backticks, like this:

```
your code goes here
```

to get some nice, Rusty formatting.