let a = [10, 20, 30, 40, 50];
let mut index_ = 0;
while index_ < 5 {
println!("{}", a[index_]); // works
println!("{a[index_]}"); // does not work
println!("{index_}"); // works
println!("{}", index_); // works
index_ = index_ + 1;
}
Why does "{a[index_]}" not work? It seems like it should to me.
The documentation says that this syntax is called "named parameters", and it supports names, not arbitrary expressions.
If a named parameter does not appear in the argument list,
format!will reference a variable with that name in the current scope.
a[index_] is not a valid name (but is a valid expression), so you get the error because the format! syntax doesn't let you use arbitrary expressions inside {}, like in Python. Note that println! "uses the same syntax as format!", so the same reasoning applies to println! as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With