How can i overwrite this int

fn wrapper() {
  let mut pwd_length: u32 = 0;
  generate_pwd_length(&mut pwd_length);
}

fn generate_pwd_length(pwd_length: &mut u32) {
     println!("Enter password length (1 - 50)");
     let mut user_pwd_length: String = String::new();
     io::stdin()
      .read_line(&mut user_pwd_length)
      .expect("Something went wrong.");
     let user_pwd_length: u32 = match user_pwd_length.trim().parse() {
       Ok(num) => num,
       Err(_) => println!("Your input not a number"),
     };
     
     pwd_length = user_pwd_length;
   }

After fixing the syntax error and adding the import, this code generates the following errors (playground):

error[E0308]: mismatched types
  --> src/lib.rs:16:19
   |
16 |         Err(_) => println!("Your input not a number"),
   |                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`, found `()`
   |
   = note: this error originates in the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0308]: mismatched types
  --> src/lib.rs:19:18
   |
8  | fn generate_pwd_length(pwd_length: &mut u32) {
   |                                    -------- expected due to this parameter type
...
19 |     pwd_length = user_pwd_length;
   |                  ^^^^^^^^^^^^^^^ expected `&mut u32`, found `u32`
   |
help: consider dereferencing here to assign to the mutable borrowed piece of memory
   |
19 |     *pwd_length = user_pwd_length;
   |     +
  • The first error essentially tells you that in case of "not_a_number input" there's nothing to put into user_pwd_length. To fix it, you must first think what do you want the program to do in this case on the larger scale (exit with an error, ask again, use some default value...).
  • The second error has the compiler suggestion and is fixed by directly applying the suggested change.
3 Likes

your solution work well on my project, thanks for helping

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.