简体   繁体   中英

Unable to populate an array of strings in a while loop in Rust

I am struggling to populate an array in Rust.

Here is my code:

use std::convert::TryInto;
use rand::rngs::mock::StepRng;

fn main() {
    println!("Blackjack!");

        let mut arr_num: [String; 10];
        let mut i = 0;
        let mut n = 2;

    // Loop while `n` is less than 101
    while n < 11 {
        arr_num[i] = n.to_string();
        // Increment counter
        n += 1;
                i += 1;
    }

    let arr: [i32; 5] = (1..=5).collect::<Vec<_>>()
            .try_into().expect("wrong size iterator");
    let mut first = StepRng::new(2, 11);
    //let mut first: [&str; 10] = ["2"; "11"];
    let mut ranks: [&str; 4] = ["JACK", "QUEEN", "KING", "ACE"];
    let mut suits: [&str; 4] = ["SPADE", "HEART", "DIAMOND", "CLUB"];

    println!("arr_num is {:?}", arr_num);
    println!("arr is {:?}", arr);
    println!("Ranks is {:?}", first);
    println!("Ranks is {:?}", ranks);
    println!("Suits is {:?}", suits);
}

I am getting this error:

error[E0381]: use of possibly-uninitialized variable: `arr_num`
  --> src/main.rs:18:3
   |
18 |         arr_num[i] = n.to_string();
   |         ^^^^^^^^^^ use of possibly-uninitialized `arr_num`

If I try this: let mut arr_num: [&str; 10]; let mut arr_num: [&str; 10];

I get this error:

error[E0308]: mismatched types
  --> src/main.rs:18:16
   |
18 |         arr_num[i] = n.to_string();
   |         ----------   ^^^^^^^^^^^^^
   |         |            |
   |         |            expected `&str`, found struct `String`
   |         |            help: consider borrowing here: `&n.to_string()`
   |         expected due to the type of this binding

error[E0283]: type annotations needed
  --> src/main.rs:18:18
   |
18 |         arr_num[i] = n.to_string();
   |                      --^^^^^^^^^--
   |                      | |
   |                      | cannot infer type for type `{integer}`
   |                      this method call resolves to `String`
   |
   = note: multiple `impl`s satisfying `{integer}: ToString` found in the `alloc` crate:
           - impl ToString for i8;
           - impl ToString for u8;

I also tried using the & like the error says to do:

error[E0381]: use of possibly-uninitialized variable: `arr_num`
  --> src/main.rs:18:3
   |
18 |         arr_num[i] = &n.to_string();
   |         ^^^^^^^^^^ use of possibly-uninitialized `arr_num`

error[E0716]: temporary value dropped while borrowed
  --> src/main.rs:18:17
   |
18 |         arr_num[i] = &n.to_string();
   |         ----------    ^^^^^^^^^^^^^- temporary value is freed at the end of this statement
   |         |             |
   |         |             creates a temporary which is freed while still in use
   |         borrow later used here
   |
   = note: consider using a `let` binding to create a longer lived value

I think what I am trying to do is pretty straight forward. So how do I populate an str array in Rust?

The loop doesn't actually have anything to do with your error, it happens the same way like this:

fn main() {
    let mut arr_num: [String; 10];

    arr_num[0] = "hi".to_string();
    
    println!("{arr_num:?}")
}

Your arr_num is getting declared , but not initialized to a value (initialization requires an assignment with = ).

It looks like you don't care about what the initial value will be since you are assigning it in the loop, so you should just initialize it to a default value (array of empty String s):

fn main() {
    let mut arr_num: [String; 10] = Default::default();

    arr_num[0] = "hi".to_string();
    
    println!("{arr_num:?}")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM