What does this piece mean

i'm at chap3 of the book and i must've missed it mentioned but i can't find a reference to this:

fn main() {
  let t = ([1; 2], [3; 4]);
  let (a, _) = t;
  println!("{}", a[0] + t.1[0]); 
}

how do you read those in square brackets when they're not arrays?

if i assume they are indeed arrays, then variable "t" is t.[0] = [1, 2] correct? and t.[1] = [3, 4] ?

so "a" = t.[0] ?

and the last line prints 4?

Maybe this helps to understand:

fn main() {
  let t = ([1; 5], [3; 10]);
  println!("t = {:?}", t);

  let u = ([1, 5], [3, 10]);
  println!("u = {:?}", u); 
}

(Playground)

Output:

t = ([1, 1, 1, 1, 1], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3])
u = ([1, 5], [3, 10])

Here t is ([1, 1], [3, 3, 3, 3]).

Here a is [1, 1].

Here a[0] is 1 and t.1 is [3, 3, 3, 3]. Thus t.1[0] is 3. And 1 + 3 == 4.

The type of an array is [T; N] where T is the type each element in the array is, and N is the length of the array.

You can use a similar syntax to initialize an array conveniently. [x; y] creates an array with y elements, each of which is initialized to x. That's what's happening in your example.

let array: [usize; 2] = [1; 2];
assert_eq!(array, [1, 1]);

Note that using this syntax to create an array requires that T implements Copy so you can't use it on a Box, for example.
However the same syntax also works with the vec! macro and you can use any Clone type there. So Box does work there, which can be a bit confusing.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.