Bug 12767 – writeln of a struct with toString returning char[N]
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P1
Component
phobos
Product
D
Version
D2
Platform
x86
OS
Windows
Creation time
2014-05-19T11:57:06Z
Last change time
2020-03-21T03:56:42Z
Keywords
rejects-valid
Assigned to
No Owner
Creator
bearophile_hugs
Comments
Comment #0 by bearophile_hugs — 2014-05-19T11:57:06Z
struct Foo {
char[3] toString() const pure {
return ['F', 'o', 'o'];
}
}
void main() {
import std.stdio;
Foo f;
writeln(f);
}
DMD 2.066alpha gives:
...\dmd2\src\phobos\std\range.d(705,9): Error: static assert "Cannot put a char[3] into a LockingTextWriter."
...\dmd2\src\phobos\std\format.d(2575,12): instantiated from here: put!(LockingTextWriter, char[3])
...\dmd2\src\phobos\std\format.d(2846,21): instantiated from here: formatObject!(LockingTextWriter, Foo, char)
...\dmd2\src\phobos\std\format.d(3167,16): instantiated from here: formatValue!(LockingTextWriter, Foo, char)
...\dmd2\src\phobos\std\format.d(440,54): ... (2 instantiations, -v to show) ...
...\dmd2\src\phobos\std\stdio.d(2528,21): instantiated from here: write!(Foo, char)
temp.d(9,12): instantiated from here: writeln!(Foo)
Returning a small fixed-size char array from a toString is sometimes useful to allow tagging toString() with @nogc.
Perhaps related: Issue 12375
Comment #1 by andrej.mitrovich — 2014-05-19T14:24:13Z
Interesting, I never thought about returning static arrays. Currently as a workaround you could implement a toString that takes a format string and an output range.
Comment #2 by bearophile_hugs — 2014-05-20T10:38:23Z
A workaround is to call the toString method:
struct Foo {
char[3] toString() const pure {
return ['F', 'o', 'o'];
}
}
void main() {
import std.stdio;
Foo f;
writeln(f.toString);
}