D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 12767 - writeln of a struct with toString returning char[N]
Summary: writeln of a struct with toString returning char[N]
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: phobos (show other issues)
Version: D2
Hardware: x86 Windows
: P1 normal
Assignee: No Owner
URL:
Keywords: rejects-valid
Depends on:
Blocks:
 
Reported: 2014-05-19 11:57 UTC by bearophile_hugs
Modified: 2020-03-21 03:56 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description bearophile_hugs 2014-05-19 11:57:06 UTC
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 Andrej Mitrovic 2014-05-19 14:24:13 UTC
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 bearophile_hugs 2014-05-20 10:38:23 UTC
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);
}
Comment 3 basile-z 2015-11-21 13:47:22 UTC
2.069 ok