Transferring 32 bits
Salih Dincer
salihdb at hotmail.com
Thu Aug 25 21:34:32 UTC 2022
On Thursday, 25 August 2022 at 12:40:57 UTC, Adam D Ruppe wrote:
> This code is completely wrong. You're improperly casting
> mutable and limited lifetime data to string, then returning it.
> And that scope res has no reason to exist; the code is
> identical to just `return cast(string) bytes;` which the
> compiler will slice for you - taking a pointer of it - then
> you return that slice with a new type.
Yes, but the code works withthe new operator. I just wanted to go
to the limits D allowed; to get some understanding of reference
types and scope...
On Thursday, 25 August 2022 at 14:17:16 UTC, Paul Backus wrote:
> ...to make toString a template that accepts an output range:
>
> ```d
> import std.range;
>
> void toString(Sink)(ref Sink sink)
> if (isOutputRange!(Sink, char))
> {
> put(sink, cast(char[]) bytes);
> }
> ```
I tried using outputrange but without success. But I implemented
like this and was able to return a living string perfectly:
```d
import std.format, std.stdio;
struct S(int len)
{
char[len] bytes;
void toString(void delegate(const(char)[]) sink) const
{
auto res = cast(char[]) bytes;
typeid(res).writeln(" toString()=>");
sink.formattedWrite("%s", res);
}
}
char[] foo(char[9] bytes)
{
auto res = cast(char[]) format("%s", S!9(bytes));
scope(exit)
typeid(res).writeln(" foo()=>");
return res;
}
void main()
{
char[9] text = " Hello D".dup;
auto test = S!9(text);
test.writeln; // ok
foo(text).writeln; // ok
}
/* Output:
char[] toString()=>
Hello D
char[] toString()=>
char[] foo()=>
Hello D
*/
```
Thank you all, it was helpful...
SDB at 79
More information about the Digitalmars-d
mailing list