Improving UFCS for Pointers to Structs
I’ve often found myself avoiding UFCS in D simply because I couldn’t use it consistently. The compiler forces me to duplicate functions when working with both values and pointers, which defeats a lot of the elegance UFCS is supposed to provide.
Here’s a minimal example:
struct Vector
{
int data;
}
void add(ref Vector self, int value)
{
self.data += value;
}
void main()
{
Vector v;
Vector* ptr = &v;
v.add(1); // Works
ptr.add(1); // Error: no matching function
}
The ptr.add(1) line fails because UFCS doesn’t automatically dereference the pointer to match the ref parameter in add. To make it work, I’d need to either call add(ptr, 1) or duplicate the function to handle Vector. Neither option feels ideal.
Suggestion
Could D support automatic UFCS for pointers to structs? That is, allow the compiler to transform ptr.add(1) into add(*ptr, 1) if the function takes a ref and ptr is a pointer to the expected type.
This would make UFCS much more usable without changing any behavior for existing code. Maybe this could be enabled via auto ref, inout ref, or something similar if implicit dereferencing is too risky to do universally.
Why This Matters
In Zig, for example, UFCS works seamlessly whether you have a value or a pointer — the compiler just figures it out. That kind of polish would be great to see in D as well.
Benefits
Less boilerplate
Cleaner, more ergonomic UFCS
Better parity with languages like Zig
No need to manually unwrap pointers just to get method-like syntax