Bug 15692 – Allow struct member initializer everywhere
Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P4
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2016-02-16T13:20:10Z
Last change time
2023-01-31T11:02:07Z
Assigned to
No Owner
Creator
Jacob Carlborg
Comments
Comment #0 by doob — 2016-02-16T13:20:10Z
Currently it's only legal to use struct member initializer when declaring a variable:
struct Foo { int a; int b; }
void main()
{
Foo foo = {
a: 3,
b: 4
};
}
It would be a big improvement if something as the following was allowed:
Foo{ a: 3, b: 4 }
Then it would be possible to use the member initializer syntax in all places a regular struct initializer is supported. For example, together with "auto" and when calling functions:
auto foo = Foo{ a: 3, b: 4 };
bar(Foo{ a: 3, b: 4 });
An alternative syntax could be to use parentheses instead:
auto foo = Foo(a: 3, b: 4);
Comment #1 by initrd.gz — 2016-04-06T01:44:08Z
My use case: Vulkan uses structs to pass large amounts of parameters around. My current code looks like this:
VkImageCreateInfo imgInfo = {
imageType: VkImageType.VK_IMAGE_TYPE_2D,
format: VkFormat.VK_FORMAT_R8G8B8A8_UNORM, // TODO: only allocate alpha if needed
extent: image.size,
mipLevels: image.mipLevels,
arrayLayers: image.layers,
samples: VkSampleCountFlagBits.VK_SAMPLE_COUNT_1_BIT,
tiling: VkImageTiling.VK_IMAGE_TILING_LINEAR, //VK_IMAGE_TILING_OPTIMAL,
usage: VkImageUsageFlagBits.VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VkImageUsageFlagBits.VK_IMAGE_USAGE_SAMPLED_BIT,
sharingMode: VkSharingMode.VK_SHARING_MODE_EXCLUSIVE,
initialLayout: VkImageLayout.VK_IMAGE_LAYOUT_PREINITIALIZED,
};
enforceVK(vkCreateImage(device, &imgInfo, null, &image.img));
It'd be really nice if it were possible to specify the struct inline with the creation call:
auto img = createImage(device, VkImageCreateInfo {
imageType: VkImageType.VK_IMAGE_TYPE_2D,
// ...
initialLayout: VkImageLayout.VK_IMAGE_LAYOUT_PREINITIALIZED,
});
It'd also be very helpful for returning info structs from lamdas:
auto queueCreateInfo = priorities
.enumerate
.filter!(x => x[1].length > 0)
.map!((x) {
VkDeviceQueueCreateInfo info = {
queueFamilyIndex: x[0],
queueCount: cast(uint) x[1].length,
pQueuePriorities: x[1].ptr,
};
return info;
})
.array;
You also basically have to use the the named field initialization syntax because each Vulkan info struct begins with a `sType` field and a `pNext` field, which at the moment should be a struct-specific constant and null that you don't really want to specify each time you create the struct.
Comment #2 by lio+bugzilla — 2017-04-26T00:32:22Z
My 2c: this is more D-like,
auto foo = cast(Foo){ a: 3, b: 4 };
Comment #3 by doob — 2017-04-26T18:47:35Z
(In reply to Lionello Lunesu from comment #2)
> My 2c: this is more D-like,
>
> auto foo = cast(Foo){ a: 3, b: 4 };
I disagree, this looks weird.