Why is println! a macro in Rust?
Macro vs Function?
A macro can be thought of as code that generates more code at compile time.
So, if you were to use macro's instead of functions in your code, you would end up getting a comparatively big executable in the end.
An easy, but mildly wrong, way to understand this is that the above statement is equivalent to copying the function body everywhere the function is called and then deleting the function definition.
A function on the other hand does not result in repetitive code and will also be pushed and popped from the process stack during execution.
Yes, but don't other languages also use a function for print?
Yes, they do. And it comes with some issues. Using println! as a macro offers the following advantages in Rust:
Type checking at compile time.
Let's take following example in C:
printf("Hello World %s", 1); //This would give a runtime error.
The error in the above statement will not be caught at compile time since the function is called with correct arguments.
Fits well with Rust's ownership system.
Consider the following piece of Rust code:
let test_variable = "test_string".to_string();
println!("{}", test_variable ); // No transfer of ownership takes place.
println!("{}", test_variable ); // Does not give error over here.
You don't have to explicitly pass a reference since it's not a function call.
Otherwise, the above code would give an error since the ownership of the test_variable would be passed to the function.
Accept an arbitrary number of arguments.
Rust does not support passing multiple arguments to a function. That would cause issues since we would need to call println with different number of arguments depending on the purpose.




