-
Notifications
You must be signed in to change notification settings - Fork 19
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
add write_fmt
method to String, to make write!
macro work without imports
#261
Comments
write_fmt
method to String, to make write!
macro work without imports
Is there precedence for this on any other types? |
Not that I am aware of. But |
One problem I could see is that the implementation of |
Even if we added such an impl, of course its |
If I understand the problem at hand, this could use inherent traits, if those ever existed. |
To add, r-a does this so frequently that we have a similar macro in our code base https://github.com/rust-lang/rust-analyzer/blob/62268e474e9165de0cdb08d3794eec4b6ef1c6cd/crates/stdx/src/macros.rs#L13-L20 (though we discard the result since it doesn't ever fail for us) |
Yeah writing to a String is never supposed to fail, but I prefer a panic over silently throwing away an error. |
Given a custom Debug/Display impl can fail even when writing to strings this proposal returning a struct S;
impl std::fmt::Display for S {
fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
Result::Err(std::fmt::Error)
}
}
fn main() {
use std::fmt::Write as _;
write!(String::new(), "{}", S).unwrap();
} |
The documentation says they are not allowed to do that, so this is a buggy |
TIL https://doc.rust-lang.org/std/fmt/struct.Error.html states
but I'll have to say that is very much not discoverable, nor does it express that I guess (was the closest I could find). I assume this is just describing the fact that the error has no payload. So ye I can't really find where this is described, aside from the comment on the |
I don't think those docs are meant to imply "no new errors during Debug/Display". I thought I had seen a fairly clear statement of that rule but I don't remember where... |
Possibly here https://github.com/rust-lang/rust/blob/cedbe5c715c1fa9359683c5f108bed2054ac258b/library/alloc/src/string.rs#L2441-L2446. I'm not sure it's normative though, since it's so buried away. Notably we panic in these cases deliberately, rather than ignoring the error, because such an error may exist. I would be opposed to changing that, for example. |
I think you mean this? https://doc.rust-lang.org/std/fmt/index.html#formatting-traits
|
Given the premise that formatting implementations "must and may only return an error if…", it would be really nice if Unfortunately, that would cause a type error in any existing code that tries to propagate (And ignoring a |
I think if we do this it should just return |
BTW, However, there is an edge case that could break: trait CustomWrite {
fn write_fmt(&self, a: std::fmt::Arguments<'_>) -> () {}
}
impl CustomWrite for String {}
write!(&mut s, ""); |
One thought I had was to add a new trait for infallible write-to-string in the prelude: mod prelude {
pub trait WriteStringInfallible {
fn write_fmt(&mut self, args: std::fmt::Arguments<'_>);
}
impl WriteStringInfallible for String {
fn write_fmt(&mut self, args: std::fmt::Arguments<'_>) {
let _ = <Self as std::fmt::Write>::write_fmt(self, args);
}
}
}
use prelude::*;
fn main() {
let mut s = String::new();
write!(s, "Hello, world!");
println!("{s}");
} Currently this results in an ambiguity error. Could we change the resolver to automatically pick an explicitly imported trait method if all of the other options are glob-imported? Then you could still do use std::fmt::Write; To use But I think an easier solution would be a way to suppress impl String {
#[suppress_must_use]
fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
<Self as fmt::Write>::write_fmt(self, args)
}
} |
On IRLO, some alternatives have been suggested to achieving the goal of "easily and efficiently extending a string with formatting": s += format_args!("hello {world}");
s.push_display(&format_args!("hello {world}")); I feel like something like this is probably preferable over my original proposal here. |
https://doc.rust-lang.org/stable/std/fmt/struct.Formatter.html#method.write_fmt |
Making The only open question for that is how to handle a misbehaving (error-returning) Display/Debug/... implementation. Panicking seems a bit cleaner than just ignoring, but might result in more generated code, which might not be worth given that the docs say:
|
It might lead to inference failures, because right now there's only one RHS type for At the very least, we'll need a crater run to gauge this. (edit): This point was also raised here: https://internals.rust-lang.org/t/mut-string-format-args/19461/18 |
IMO we should definitely panic on errors when debug assertions are enabled. There's no good reason to silently ignore what is clearly a bug. I have less of a strong opinion for builds without debug assertions. |
We discussed this in a recent libs-api meeting. We don't think we should be adding an inherent A few of the possible directions are a Unfortunately, implementing the The other possible directions might be made impossible or much trickier if we were to add an inherent |
I wouldn't rule out |
Proposal
Problem statement
It would be great if this code compiled:
Using
write!
to append to aString
is one of these neat Rust things that are not obvious to discover, but once you know about it it is amazingly useful.Solution sketch
The code currently fails saying that
io::Write
orfmt::Write
needs to be imported or awrite_fmt
method needs to be added. (The right trait to import isfmt::Write
, as I found out by trial-and-error.)From the error message it sounds like that could be avoided if we simply added a
write_fmt
inherent method toString
. That would just get one minor roadblock out of the way which sounds like a win to me. :)Alternatives
We could decide the roadblock isn't bad enough to warrant doing anything.
What happens now?
This issue is part of the libs-api team API change proposal process. Once this issue is filed the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.
Possible responses
The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):
Second, if there's a concrete solution:
The text was updated successfully, but these errors were encountered: