我在初始化固定长度数组时遇到问题. 到目前为止,我的尝试都导致了"使用可能未初始化的变量:foo_array"错误:
#[derive(Debug)]
struct Foo { a: u32, b: u32 }
impl Default for Foo {
fn default() -> Foo { Foo{a:1, b:2} }
}
pub fn main() {
let mut foo_array: [Foo; 10];
// Do something here to in-place initialize foo_array?
for f in foo_array.iter() {
println!("{:?}", f);
}
}
Run Code Online (Sandbox Code Playgroud)
error[E0381]: use of possibly uninitialized variable: `foo_array`
--> src/main.rs:13:14
|
13 | for f in foo_array.iter() {
| ^^^^^^^^^ use of possibly uninitialized `foo_array`
Run Code Online (Sandbox Code Playgroud)
我实现了Default …
我需要将数组的每个元素初始化为非常量表达式.我是否可以这样做而无需先将数组的每个元素初始化为一些无意义的表达式?以下是我希望能够做到的一个例子:
fn foo(xs: &[i32; 1000]) {
let mut ys: [i32; 1000];
for (x, y) in xs.iter().zip(ys.iter_mut()) {
*y = *x / 3;
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
此代码给出了编译时错误:
error[E0381]: borrow of possibly uninitialized variable: `ys`
--> src/lib.rs:4:33
|
4 | for (x, y) in xs.iter().zip(ys.iter_mut()) {
| ^^ use of possibly uninitialized `ys`
Run Code Online (Sandbox Code Playgroud)
要解决这个问题,我需要更改函数的第一行,ys用一些虚拟值初始化元素,如下所示:
let mut ys: [i32; 1000] = [0; 1000];
Run Code Online (Sandbox Code Playgroud)
有没有办法省略额外的初始化?将所有内容包装在unsafe块中似乎没有任何区别.
我有以下代码:
const N: usize = 10000;
const S: usize = 7000;
#[derive(Copy, Clone, Debug)]
struct T {
a: f64,
b: f64,
f: f64
}
fn main() {
let mut t: [T; N] = [T {a: 0.0, b: 0.0, f: 0.0}; N];
for i in 0..N {
t[i].a = 0.0;
t[i].b = 1.0;
t[i].f = i as f64 * 0.25;
}
for _ in 0..S {
for i in 0..N {
t[i].a += t[i].b * t[i].f;
t[i].b -= t[i].a * t[i].f; …Run Code Online (Sandbox Code Playgroud)