On Thursday, 23 November 2023 at 20:13:59 UTC, BoQsc wrote:
Nothing wrong. It would be just a more concise compact way to do the same.

Also I mostly wanted to know if something like that is already possible in D language.

It's not a huge loss if it is not possible.

This is possible in Go: you dereference a literal constructor and it's either built on the stack or the heap depending on escape analysis. Example:

```go
package main

import "fmt"

type T struct {
        data [5]byte
}

func usebuffer(a *T) *T {
        a.data[0] = 1
        a.data[4] = 10
        return a
}

func f() *T {
        return usebuffer(&T{}) // <--
}

func main() {
        fmt.Println(f())
}
```

which is very close to this D that is explicitly allocating on the heap:

```d
class T {
        byte[5] data;
}

T usebuffer(T a) {
        a.data[0] = 1;
        a.data[4] = 10;
        return a;
}

T f() {
        return usebuffer(new T()); // <--
}

void main() {
        import std.stdio : writeln;
        writeln(f().data);
}
```

Which if you want stack allocation, is very similar to:

```d
class T {
        byte[5] data;
}

T usebuffer(T a) {
        a.data[0] = 1;
        a.data[4] = 10;
        return a;
}

void main() {
        import std.stdio : writeln;
        import std.typecons : scoped;

        writeln(usebuffer(scoped!T).data);
}
```

but, I don't actually know if this is safe.

Reply via email to