Printing a slice


#1

I’m wondering about the difference in println! treatment of arrays and slices.

I can do this:

let u = [2, 4, 8];
println!("{:?}", u);
println!("{:?}", &u);
println!("{:?}", &u[0..]);

But not this:

println!("{:?}", u[0..]);

So I have a few questions:

  • Why are arrays and slices treated syntactically differently by println! macro?
  • Where is this difference documented?
  • Where can I find the official slice syntax documentation (i.e. for u[a..b] etc.)?

#2

+1 on this. I also wondered and wanted to ask exactly this several times, but somehow was too lazy to submit.
Great thing you weren’t :wink:

Commenting here to get on /cc list.


#3

let u = [2, 4, 8];

This is a fixed-size array, [i32; 3].
&u is a reference to it of type &[i32; 3].

u[..] is [i32], which is an unsized array. One can do very little with unsized values directly so you take a slice instead: &u[..] of type &[i32].


#4

but then again, the println! macro takes a reference to everything you pass to it, so technically that should work automatically, shouldn’t it?


#5

Before the reference is taken you need to store the value on the stack and that requires knowing its size statically.