I'm trying to override the toString method inside a class in the D language.
override string toString() {
auto a = to!string(a);
auto b = to!string(b);
return "%s / %s", a, b;
}
I'm then creating an object called foo inside main() and then doing:
writeln(foo);
Assuming a = 1 and b = 2, I want to get this string literal printed out:
1 / 2
Instead, I only get the last number printed out
2
I'm assuming string formatting doesn't work this way when returning.
Wow. I've never seen anyone try that. No, that's not going to work. toString
is like any other function that returns a string
. There's nothing special about it except that some library functions (such as format
and writeln
) know to call it in order to convert an object to a string
. So, you'd get exactly the same behavior if you did
string convToString(Foo foo)
{
auto a = to!string(foo.a);
auto b = to!string(foo.b);
return "%s / %s", a, b;
}
and then did
writeln(convToString(foo));
But what's biting you here is the comma operator. When it runs,
return "%s / %s", a, b;
is going to become
return "%s / %s", "1", "2";
and the result of the comma operator is its last argument, so "2"
gets returned. And since "%s / %s"
, and "1"
have no side effects, they're pretty much pointless. At that point, you might as well have just written
return b;
rather than
return "%s / %s", a, b;
What you want to do is to use std.string.format
. and change your toString
function to
override string toString()
{
return format("%s / %s", a, b);
}
format
will then create the string
that you want.
On a side note, naming a local variable the same as a member variable as you did in your example is pretty much just asking for bugs, since it becomes easy to confuse the local variables and the member variables at that point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With