-
Notifications
You must be signed in to change notification settings - Fork 26
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
There should be a Printable trait all primitive types inherit by default. #574
Comments
It would be good to have a short description of how Rust does it in this issue! In general I agree with this -- I have somewhere at some point proposed a trait with such a function. I dislike names like Printable and Show, and prefer something that talks about the string representation of something. But this is a minor point. |
Another note, the print functions should require this trait. All objects that would like to be printable has to implement it. That way you only need to pass a reference to the object when you want to print it. |
This is a stolen example of how rust does it. struct MyStruct {
a: i32,
b: i32
}
impl std::fmt::Display for MyStruct {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "(value a: {}, value b: {})", self.a, self.b)
}
}
fn main() {
let test = MyStruct { a: 0, b: 0 };
println!("Used Display: {}", test);
} |
The thing which seems easiest to understand (and implement for new programmers) is probably something like a "serialize" function, which returns a string representation of the object. So foo.serialize() returns a string and print(foo) de-sugars to something like print(foo.serialize()). Seems nicer then that middle bit of what rust does. Also, then it's possible to have a default implementation for all objects (concatenating all their fields which are serialize-able in some way). |
That is pretty much what the Rust example does. Except it directly writes to a given reference instead of returning a String. The middle bit is the user implementation of the trait. |
Yea, its the writing to a reference bit I think would be nice to avoid. |
Some of the infrastructure that gives methods to maybes, futures, arrays in #698 could possibly be used to realise this. |
There should be a "Printable" trait that all objects can implement, and that all primitive datatypes inherit by default. This would enable me to define that a given argument has to be printable. Maybe it should be done like or similar to the way Rust handles it.
The text was updated successfully, but these errors were encountered: