Assigning to array of structs with custom constructor

rassoc rassoc at posteo.de
Mon Apr 25 16:11:47 UTC 2022


On 4/25/22 16:36, cc via Digitalmars-d-learn wrote:
> ```d
> struct Foo {
>      string s;
>      this(string s) { this.s = s; }
> }
> Foo foo = "a";
> Foo[] foos = ["a"]; // Error: cannot implicitly convert expression `["a"]` of type `string[]` to 
> `Foo[]`
> Foo[] foos = cast(Foo[]) ["a"]; // Error: e2ir: cannot cast `"a"` of type `string` to type `Foo`
> ```
> 
> Was there a way to do this?  I thought I recalled seeing something like this before, but I can't 
> seem to find it.

This works:

```d
import std;

void main() {
     struct Foo { string s; }
     Foo[] arr = ["abc", "def", "ghi"].map!Foo.array;
     arr.writeln; // => [Foo("abc"), Foo("def"), Foo("ghi")]
}
```


More information about the Digitalmars-d-learn mailing list