I am new to Rust and want to understand concepts such as borrowing. I am trying to create a simple two-dimensional array using standard input. Code:
use std::io; fn main() { let mut values = [["0"; 6]; 6]; // 6 * 6 array // iterate 6 times for user input for i in 0..6 { let mut outputs = String::new(); io::stdin().read_line(&mut outputs).expect( "failed to read line", ); // read space separated list 6 numbers. Eg: 5 7 8 4 3 9 let values_itr = outputs.trim().split(' '); let mut j = 0; for (_, value) in values_itr.enumerate() { values[i][j] = value; j += 1; } } }
This does not compile because the lifetime of the outputs variable is not long enough:
error[E0597]: `outputs` does not live long enough --> src/main.rs:20:5 | 14 | let values_itr = outputs.trim().split(' '); | ------- borrow occurs here ... 20 | } | ^ `outputs` dropped here while still borrowed 21 | } | - borrowed value needs to live until here
How can I get iterated values ββfrom a block to an array of values?
source share