Why does the Rust compiler give an uninitialized variable error when initializing an array in a loop?












1















The compiler complains a variable is not initialized, and it is right.
However, the variable appears on the left side of the expression.



I guess I could easily fix this by initializing the array, but I am more interested in understanding why the compiler thinks this is an error condition.



I don't think this would be flagged as an error in other languages.



Here is my code:



fn main() {
const LEN: usize = 5;
let mut arr: [u32; LEN];

for i in 0..LEN {
arr[i] = fib(i as u32);
}

println!("{:?}", arr);
}

fn fib(n: u32) -> u32 {
match n {
0 => 0,
1 => 1,
_ => fib(n - 1) + fib(n - 2),
}
}


Here is the error:



error[E0381]: use of possibly uninitialized variable: `arr`
--> src/main.rs:6:9
|
6 | arr[i] = fib(i as u32);
| ^^^^^^^^^^^^^^^^^^^^^^ use of possibly uninitialized `arr`

error[E0381]: use of possibly uninitialized variable: `arr`
--> src/main.rs:9:22
|
9 | println!("{:?}", arr);
| ^^^ use of possibly uninitialized `arr`









share|improve this question




















  • 1





    The compiler isn't smart enough, however Rust give a lot of tool to make better code than this Iterator is the way to go or std::mem::uninitialized if you want keep an array is the "trust me" solution.

    – Stargateur
    Nov 25 '18 at 22:24













  • Thanks for pointing out std::mem::uninitialized. A quick search brought me to this page that shows some code very similar to mine: doc.rust-lang.org/std/mem/fn.uninitialized.html

    – Muffo
    Nov 26 '18 at 2:42






  • 1





    See also What is the proper way to initialize a fixed length array?; Initialize array holding struct more efficiently; Is there a way to not have to initialize arrays twice?.

    – Shepmaster
    Nov 26 '18 at 13:42
















1















The compiler complains a variable is not initialized, and it is right.
However, the variable appears on the left side of the expression.



I guess I could easily fix this by initializing the array, but I am more interested in understanding why the compiler thinks this is an error condition.



I don't think this would be flagged as an error in other languages.



Here is my code:



fn main() {
const LEN: usize = 5;
let mut arr: [u32; LEN];

for i in 0..LEN {
arr[i] = fib(i as u32);
}

println!("{:?}", arr);
}

fn fib(n: u32) -> u32 {
match n {
0 => 0,
1 => 1,
_ => fib(n - 1) + fib(n - 2),
}
}


Here is the error:



error[E0381]: use of possibly uninitialized variable: `arr`
--> src/main.rs:6:9
|
6 | arr[i] = fib(i as u32);
| ^^^^^^^^^^^^^^^^^^^^^^ use of possibly uninitialized `arr`

error[E0381]: use of possibly uninitialized variable: `arr`
--> src/main.rs:9:22
|
9 | println!("{:?}", arr);
| ^^^ use of possibly uninitialized `arr`









share|improve this question




















  • 1





    The compiler isn't smart enough, however Rust give a lot of tool to make better code than this Iterator is the way to go or std::mem::uninitialized if you want keep an array is the "trust me" solution.

    – Stargateur
    Nov 25 '18 at 22:24













  • Thanks for pointing out std::mem::uninitialized. A quick search brought me to this page that shows some code very similar to mine: doc.rust-lang.org/std/mem/fn.uninitialized.html

    – Muffo
    Nov 26 '18 at 2:42






  • 1





    See also What is the proper way to initialize a fixed length array?; Initialize array holding struct more efficiently; Is there a way to not have to initialize arrays twice?.

    – Shepmaster
    Nov 26 '18 at 13:42














1












1








1








The compiler complains a variable is not initialized, and it is right.
However, the variable appears on the left side of the expression.



I guess I could easily fix this by initializing the array, but I am more interested in understanding why the compiler thinks this is an error condition.



I don't think this would be flagged as an error in other languages.



Here is my code:



fn main() {
const LEN: usize = 5;
let mut arr: [u32; LEN];

for i in 0..LEN {
arr[i] = fib(i as u32);
}

println!("{:?}", arr);
}

fn fib(n: u32) -> u32 {
match n {
0 => 0,
1 => 1,
_ => fib(n - 1) + fib(n - 2),
}
}


Here is the error:



error[E0381]: use of possibly uninitialized variable: `arr`
--> src/main.rs:6:9
|
6 | arr[i] = fib(i as u32);
| ^^^^^^^^^^^^^^^^^^^^^^ use of possibly uninitialized `arr`

error[E0381]: use of possibly uninitialized variable: `arr`
--> src/main.rs:9:22
|
9 | println!("{:?}", arr);
| ^^^ use of possibly uninitialized `arr`









share|improve this question
















The compiler complains a variable is not initialized, and it is right.
However, the variable appears on the left side of the expression.



I guess I could easily fix this by initializing the array, but I am more interested in understanding why the compiler thinks this is an error condition.



I don't think this would be flagged as an error in other languages.



Here is my code:



fn main() {
const LEN: usize = 5;
let mut arr: [u32; LEN];

for i in 0..LEN {
arr[i] = fib(i as u32);
}

println!("{:?}", arr);
}

fn fib(n: u32) -> u32 {
match n {
0 => 0,
1 => 1,
_ => fib(n - 1) + fib(n - 2),
}
}


Here is the error:



error[E0381]: use of possibly uninitialized variable: `arr`
--> src/main.rs:6:9
|
6 | arr[i] = fib(i as u32);
| ^^^^^^^^^^^^^^^^^^^^^^ use of possibly uninitialized `arr`

error[E0381]: use of possibly uninitialized variable: `arr`
--> src/main.rs:9:22
|
9 | println!("{:?}", arr);
| ^^^ use of possibly uninitialized `arr`






rust






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 26 '18 at 13:40









Shepmaster

152k14299436




152k14299436










asked Nov 25 '18 at 21:07









MuffoMuffo

1,11211321




1,11211321








  • 1





    The compiler isn't smart enough, however Rust give a lot of tool to make better code than this Iterator is the way to go or std::mem::uninitialized if you want keep an array is the "trust me" solution.

    – Stargateur
    Nov 25 '18 at 22:24













  • Thanks for pointing out std::mem::uninitialized. A quick search brought me to this page that shows some code very similar to mine: doc.rust-lang.org/std/mem/fn.uninitialized.html

    – Muffo
    Nov 26 '18 at 2:42






  • 1





    See also What is the proper way to initialize a fixed length array?; Initialize array holding struct more efficiently; Is there a way to not have to initialize arrays twice?.

    – Shepmaster
    Nov 26 '18 at 13:42














  • 1





    The compiler isn't smart enough, however Rust give a lot of tool to make better code than this Iterator is the way to go or std::mem::uninitialized if you want keep an array is the "trust me" solution.

    – Stargateur
    Nov 25 '18 at 22:24













  • Thanks for pointing out std::mem::uninitialized. A quick search brought me to this page that shows some code very similar to mine: doc.rust-lang.org/std/mem/fn.uninitialized.html

    – Muffo
    Nov 26 '18 at 2:42






  • 1





    See also What is the proper way to initialize a fixed length array?; Initialize array holding struct more efficiently; Is there a way to not have to initialize arrays twice?.

    – Shepmaster
    Nov 26 '18 at 13:42








1




1





The compiler isn't smart enough, however Rust give a lot of tool to make better code than this Iterator is the way to go or std::mem::uninitialized if you want keep an array is the "trust me" solution.

– Stargateur
Nov 25 '18 at 22:24







The compiler isn't smart enough, however Rust give a lot of tool to make better code than this Iterator is the way to go or std::mem::uninitialized if you want keep an array is the "trust me" solution.

– Stargateur
Nov 25 '18 at 22:24















Thanks for pointing out std::mem::uninitialized. A quick search brought me to this page that shows some code very similar to mine: doc.rust-lang.org/std/mem/fn.uninitialized.html

– Muffo
Nov 26 '18 at 2:42





Thanks for pointing out std::mem::uninitialized. A quick search brought me to this page that shows some code very similar to mine: doc.rust-lang.org/std/mem/fn.uninitialized.html

– Muffo
Nov 26 '18 at 2:42




1




1





See also What is the proper way to initialize a fixed length array?; Initialize array holding struct more efficiently; Is there a way to not have to initialize arrays twice?.

– Shepmaster
Nov 26 '18 at 13:42





See also What is the proper way to initialize a fixed length array?; Initialize array holding struct more efficiently; Is there a way to not have to initialize arrays twice?.

– Shepmaster
Nov 26 '18 at 13:42












1 Answer
1






active

oldest

votes


















5














When you do a for loop, the code is sequential: the compiler first set the value at index 0, then 1, etc. but it has no clue that you are initializing the array that way. You could, for example, forgot the last index, and your code would be invalid.



To say it simply: you can modify a variable only when it was initialized, and arr is your variable, not arr[0].



When you index something in Rust, this is desugared into the index_mut method. In your situation, you are calling a method of arr that is an uninitialized variable.





As you said, the solution to your issue is to initialize your array first, with zeroes for example:



fn main() {
const LEN : usize = 5;
let mut arr = [0; LEN];

for i in 0..LEN {
arr[i] = fib(i as u32);
}

println!("{:?}", arr);
}


fn fib(n: u32) -> u32 {
match n {
0 => 0,
1 => 1,
_ => fib(n-1) + fib(n-2)
}
}





share|improve this answer


























  • Thanks for the great explanation and for the link!

    – Muffo
    Nov 26 '18 at 2:41











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53471996%2fwhy-does-the-rust-compiler-give-an-uninitialized-variable-error-when-initializin%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









5














When you do a for loop, the code is sequential: the compiler first set the value at index 0, then 1, etc. but it has no clue that you are initializing the array that way. You could, for example, forgot the last index, and your code would be invalid.



To say it simply: you can modify a variable only when it was initialized, and arr is your variable, not arr[0].



When you index something in Rust, this is desugared into the index_mut method. In your situation, you are calling a method of arr that is an uninitialized variable.





As you said, the solution to your issue is to initialize your array first, with zeroes for example:



fn main() {
const LEN : usize = 5;
let mut arr = [0; LEN];

for i in 0..LEN {
arr[i] = fib(i as u32);
}

println!("{:?}", arr);
}


fn fib(n: u32) -> u32 {
match n {
0 => 0,
1 => 1,
_ => fib(n-1) + fib(n-2)
}
}





share|improve this answer


























  • Thanks for the great explanation and for the link!

    – Muffo
    Nov 26 '18 at 2:41
















5














When you do a for loop, the code is sequential: the compiler first set the value at index 0, then 1, etc. but it has no clue that you are initializing the array that way. You could, for example, forgot the last index, and your code would be invalid.



To say it simply: you can modify a variable only when it was initialized, and arr is your variable, not arr[0].



When you index something in Rust, this is desugared into the index_mut method. In your situation, you are calling a method of arr that is an uninitialized variable.





As you said, the solution to your issue is to initialize your array first, with zeroes for example:



fn main() {
const LEN : usize = 5;
let mut arr = [0; LEN];

for i in 0..LEN {
arr[i] = fib(i as u32);
}

println!("{:?}", arr);
}


fn fib(n: u32) -> u32 {
match n {
0 => 0,
1 => 1,
_ => fib(n-1) + fib(n-2)
}
}





share|improve this answer


























  • Thanks for the great explanation and for the link!

    – Muffo
    Nov 26 '18 at 2:41














5












5








5







When you do a for loop, the code is sequential: the compiler first set the value at index 0, then 1, etc. but it has no clue that you are initializing the array that way. You could, for example, forgot the last index, and your code would be invalid.



To say it simply: you can modify a variable only when it was initialized, and arr is your variable, not arr[0].



When you index something in Rust, this is desugared into the index_mut method. In your situation, you are calling a method of arr that is an uninitialized variable.





As you said, the solution to your issue is to initialize your array first, with zeroes for example:



fn main() {
const LEN : usize = 5;
let mut arr = [0; LEN];

for i in 0..LEN {
arr[i] = fib(i as u32);
}

println!("{:?}", arr);
}


fn fib(n: u32) -> u32 {
match n {
0 => 0,
1 => 1,
_ => fib(n-1) + fib(n-2)
}
}





share|improve this answer















When you do a for loop, the code is sequential: the compiler first set the value at index 0, then 1, etc. but it has no clue that you are initializing the array that way. You could, for example, forgot the last index, and your code would be invalid.



To say it simply: you can modify a variable only when it was initialized, and arr is your variable, not arr[0].



When you index something in Rust, this is desugared into the index_mut method. In your situation, you are calling a method of arr that is an uninitialized variable.





As you said, the solution to your issue is to initialize your array first, with zeroes for example:



fn main() {
const LEN : usize = 5;
let mut arr = [0; LEN];

for i in 0..LEN {
arr[i] = fib(i as u32);
}

println!("{:?}", arr);
}


fn fib(n: u32) -> u32 {
match n {
0 => 0,
1 => 1,
_ => fib(n-1) + fib(n-2)
}
}






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 25 '18 at 21:43

























answered Nov 25 '18 at 21:11









Darth BoiethiosDarth Boiethios

10.6k43775




10.6k43775













  • Thanks for the great explanation and for the link!

    – Muffo
    Nov 26 '18 at 2:41



















  • Thanks for the great explanation and for the link!

    – Muffo
    Nov 26 '18 at 2:41

















Thanks for the great explanation and for the link!

– Muffo
Nov 26 '18 at 2:41





Thanks for the great explanation and for the link!

– Muffo
Nov 26 '18 at 2:41


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53471996%2fwhy-does-the-rust-compiler-give-an-uninitialized-variable-error-when-initializin%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Contact image not getting when fetch all contact list from iPhone by CNContact

count number of partitions of a set with n elements into k subsets

A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks