3 ms·
like all generic interfaces in Rust, printing takes arguments by reference, regardless of whether they are Copy or not. The println! macro hides this from
by Too 10y ago
like all generic interfaces in Rust, printing takes arguments by reference,
regardless of whether they are Copy or not. The println! macro hides this from
you by implicitly borrowing the arguments,
What's the reason for this? Seems a bit inconsistent that for functions you must explicitly pass with &, but for print it's automatic.
- dbaupp 10y agoThe reason I can think of are: - it'd be annoying to have to write `println!("{}", &s);`, - this is not an inconsistency one thinks about in practice: ownership is important in Rust, but the compiler does all the annoying checking, so IME one can just let it fade into the background and not think about it until the compiler tells you there's a problem, - it's an "permissive" inconsistency: writing a & will still compile and give the same output, - it's a syntax-level inconsistency created by the println! macro packaging up the normal syntax, not some special rules for special functions: there's still a literal & borrow in there (see the macro expansion), - historical reasons, and no-one was annoyed enough (or even noticed it enough) to change it.
- Too 10y agoHmm. If people would think it was annoying to println!("{}", &s) they wouldnt use rust in the first place because you have to do that everywhere else for plain functions. Beeing permissive makes it even worse as there are now 2 inconsistent ways to do the same thing. Maybe I need to understand rust macros better. I guess this all boils down to: macros are a very bad idea, as in other programming languages.
- acqq 10y agoAnd if print can already have a special treatment, it should surely be the one where the value is copied if can fit the basic type size, that is, at least for int like and float like stuff not have automatic pass by reference but automatic pass by value to it?
- JelteF 10y agoThe problem with this is print is a macro and that macros are expanded before the type checker. This makes it impossible to know if something can be copied or not, because this is type information.
- acqq 10y agoI believe it could be a solvable problem? Imagine that the macro expands every parameter x to some language construct f( x ) where f( x ) has access to the type of x and the type of its result is different depending of the type of x, returning a value for for int and float-like variables, and the reference for others.