Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does println! inline variable syntax look inconsistent?

Tags:

syntax

rust

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.

like image 738
atari_61 Avatar asked Jun 22 '26 08:06

atari_61


1 Answers

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.

like image 146
ForceBru Avatar answered Jun 24 '26 22:06

ForceBru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!