我正在努力在 Rust 中填充一個陣列。
這是我的代碼:
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);
}
我收到此錯誤:
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`
如果我試試這個:let mut arr_num: [&str; 10];
我收到此錯誤:
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;
我也嘗試使用&錯誤所說的方法:
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
我認為我正在嘗試做的事情非常簡單。那么如何在 Rust 中填充 str 陣列呢?
uj5u.com熱心網友回復:
回圈實際上與您的錯誤沒有任何關系,它的發生方式與此相同:
fn main() {
let mut arr_num: [String; 10];
arr_num[0] = "hi".to_string();
println!("{arr_num:?}")
}
您arr_num正在宣告,但未初始化為值(初始化需要使用 賦值=)。
看起來您并不關心初始值是什么,因為您是在回圈中分配它,因此您應該將其初始化為默認值(空陣列String):
fn main() {
let mut arr_num: [String; 10] = Default::default();
arr_num[0] = "hi".to_string();
println!("{arr_num:?}")
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/483013.html
下一篇:二維動態陣列指標訪問
