Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to assign default values to tuple struct members

How to automatically assign default values to tuple struct members

struct A(f64, i32);

fn main() {
    let mut a: A; // expect a.0 = 0.0, a.1 = 0
    // even below 2 line code doesn't compile
    // a.0 = 1.2;
    // a.1 = 3;

    println!("{}, {}", a.0, a.1);
}

But I’m getting below error

error[E0381]: used binding `a` isn't initialized
 --> src/main.rs:5:24
  |
4 |     let mut a: A; // expect a.0 = 0.0, a.1 = 0
  |         ----- binding declared here but left uninitialized
5 |     println!("{}, {}", a.0, a.1);
  |                        ^^^ `a.0` used here but it isn't initialized
  |

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Add #[derive(Default)] and initialize with A::default (or Default::default()):

#[derive(Default)]
struct A(f64, i32);

fn main() {
    let mut a = A::default(); // expect a.0 = 0.0, a.1 = 0
    
    println!("{}, {}", a.0, a.1);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading