3 ms·
> almost zero mainstream (statically typed) programming languages can even let you write down that you want a non-empty string. Today D will fulfill your dream
by WalterBright 5y ago
> almost zero mainstream (statically typed) programming languages can even let you write down that you want a non-empty string.
Today D will fulfill your dreams!
struct MyString {
private string s = "error";
alias s this;
this(string s) {
assert(s.length);
this.s = s;
}
}
void main() {
MyString ms = "hello";
test(ms);
MyString mserror = ""; // runtime assert fail
}
void test(string s) { }
- Leherenn 5y agoWould it be possible to have a static assert? In that case I would expect it to fail at compile time, not run time.
- WalterBright 5y agoYou can use static asserts if you turn the constructor into a template and pass the initializer into a compile time parameter.
- mhh__ 5y agoNo. If D had unlimited access to C code at CTFE then maybe you could implement refinement types at compile time as a library but for now you are stuck with what Walter has posted. I implemented a sketch of the API for this ages ago but the actual type checking had to be done at module load time because was of aforementioned (justified) restrictions to CTFE Dependant types are a whole other monster.
- ragnese 5y agoI love that! So it's the `alias s this` that's the magic here, I assume? It's making the `this` pointer actually point to the stored field? That's awesome!