#[allow(dead_code)] //# [allow(unused_variables)] /* arrays, in Rust - syntax for the type - syntax for initalizing - looping over: via index, via each, via both (enumerated). - they are ON THE STACK! - when passed(*): copied, the stack - Using '&' creates an *array slice* -- a struct that has a size *and* a pointer to the (borrowed) data. - Using '&mut' creates a slice that the recipient can modify. An object can be borrowed (&) read-only many times. But it can only be mutably-borrowed (&mut) once, at any moment. (*) More precisely: The array is copied *if* it contains elements that implement the 'Copy' trait. Primitive numbers, booleans, and characters DO implement Copy. (as do tuples-of-Copy-able, array-of-Copy-able .. but not struct-of-Copy-able, unless you annotate it yourself! `#[derive(Copy)]` ) If an array isn't copyable, you can *only* pass around borrowings/slices of it! */ const N: usize = 7; fn main() { println!("*******************************"); let mut temps: [f64; N] = [20.5; N]; println!("temps is {:?}", temps); for i in 0..temps.len() { println!("temps[{}] holds {}.", i, temps[i]); } for t in temps { println!("temps holds {}.", t); } for (i,t) in temps.iter().enumerate() { println!("temps[{}] holds {} (which is of course temps[{}]).", i, t, temps[i]); } //let i : i32; for i in 0..N { // Can only assign if we use `let MUT temps = …` above temps[i] = 3.0 * (i as f64); } println!("temps is {:?}", temps); println!("The sum of all is {}.", sum(&temps) ); println!("The sum of 2..4 is {}.", sum(&temps[2..4]) ); println!("The sum is {}.", sum_and_modify(&mut temps[2..4]) ); println!("temps is {:?}", temps); } fn sum_for_sz7( data : [f64; N] ) -> f64 { let mut sum_so_far = 0.0; for x in data { sum_so_far += x; } return sum_so_far; } fn sum( data : &[f64] ) -> f64 { let mut sum_so_far = 0.0; for i in 0..(*data).len() { sum_so_far += data[i]; } // the '*' is implicit. //equiv: for x in data { sum_so_far += x; } // Is really: `for x in *data {…}` return sum_so_far; } fn sum_and_modify( data : &mut[f64] ) -> f64 { let mut sum_so_far = 0.0; for i in 0..data.len() { sum_so_far += data[i]; data[i] = 99.0; // Mutate the array's contents! } //data[1000] = -99.0; //Will cause a run-time error, if out-of-bounds. return sum_so_far; } fn make_new_array_of_size(i32: desired_size) -> &[f64] { let my_fancy_new_array: [f64; ???] = ??? return &my_fancy_new_array; } fn foo() { let s1: String = String::from("hi"); my_print(s1); // s1 has been moved!; I can't use it. } fn my_print( msg: String ) -> String { println!("{}", &msg); return msg; }