Hacker News new | ask | show | jobs
by dwattttt 334 days ago
email_t doesn't have to be opaque; if it's just a visible wrapper around char* then you can still do everything with it as a char* (that is, everything you do with strings).

The benefit is to avoid treating char*s as email_t, not avoiding treating email_t as char*.

2 comments

(Using a thin wrapper like this to add safety is called the newtype pattern, if anyone wants to know.)
I was curious how this would look in C, and I found this article[1] how this could look in C, apparently with very little overhead.

And as I just saw, Python 3.10 also introduced a NewType[2] wrapper. I'll have to see how that feels to handle.

1: https://blog.nelhage.com/2010/10/using-haskells-newtype-in-c...

2: https://typing.python.org/en/latest/spec/aliases.html#newtyp...

Python’s NewType is, confusingly, a very different thing: it’s a compile-time-only subtype of the original, rather than a Haskell-style newtype (which is an entirely separate type from its source).
I've re-read the article again since getting a bunch of up and down votes across the comment section, and I think you've chosen a better name for this article than PdV. It really is just about using newtype wrappers.
In the example code they explicitly put the struct in the c file so the char* is not available.

If you're suggesting getting around this by casting an email_t* to char* then I wish you good luck on your adventures. There's some times you gotta do stuff like that but this ain't it.

You could probably get away with the typecast if you satisfy the "common struct prefix" requirement, that's nowhere near necessary.

While the article does hide the internal char*, that's not strictly necessary to get the benefit of "parse, don't validate". Hide implementation details sure, but not everything is an implementation detail.