What is the difference between these codes?

Hello,
both of these codes print Hello, World!, but what is the difference between them and which one is more correct?

fn main ()
{
print!("Hello, World!");
}

And

fn main ()
{
print!("{}", "Hello, World!");
}

Is {} mandatory?

Please answer this question briefly.

Thank you.

The {}is intended as a place holder for any variables you want to print in your output string. If you have no variables, as in this case, then you don't need the braces.

1 Like

Hello,
Thank you so much for your reply.
So, if I have a variable that holds a string like "Hello, World!", then my code must be:

print!("{}", varibale);

Am I right?

Yep.

1 Like

Hello,
Thank you so much for your reply.

Yes. And in recent Rust releases you can also do this:

println!("{variable}");`

Which is nice when you want to say something like this, for variables x, y and z:

println!("x = {x}, y = {y}, z = {z}");

rather than:

println!("x = {}, y = {}, z = {}", x, y, z);
1 Like

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.