3 ms·
Is it just me that doesn't see a problem with the manual approach at all? Surely, there may be a better way to keep this in sync, but this is not very high effo
by lucasyvas 5y ago
Is it just me that doesn't see a problem with the manual approach at all? Surely, there may be a better way to keep this in sync, but this is not very high effort.
Unrelated, but I can't help but think this should use try_from or even potentially panic. If you get an error type you don't recognize, that could pose a risk.
At least with the manual approach you can decide if particular ranges are safe to ignore or not and do something different. Granted, I'm dreaming up scenarios that are very likely outside the author's intention, so I don't think my thoughts on the matter necessarily refute anything being said.
- codeflo 5y agoAs you hint at in your last paragraph, it’s probably hard to come up with a blog-sized example for any programming technique. If 10-15 lines were really the extent our scope, we probably wouldn’t need anything more advanced than assembler. Some amount of imagination is necessary to consider whether an idea is useful in production code, so we all have different examples in mind. Personally, I’ve had cases where three or four places had to be kept in sync, and the list was changing frequently enough that something like this became useful. Even then, it’s still a judgement call whether code generation or (if available) macros are worth the complexity. The decision might also heavily depend on the experience of the team.
- couchand 5y agoThe API in the article is try_from by another name... but leaving the question of panicking to the caller seems right to me. In the "I'm trying to respond to the error" case maybe unknown should be a panic, but what about when you share code with your log parser?
- mplanchard 5y agoI think the difference is that the try_from implementation can’t be exhaustive because the input value space is much larger than the enum space, so nothing really requires you to add the new variant to that impl when you add the variant to the enum. This provides a non-macro solution that forces the two to stay in sync, which is pretty nice if you either don’t like macros or don’t feel comfortable building them yet. I agree with the author it’s also definitely more readable and obvious than a macro, even if the whole approach makes me feel a bit weird at first blush.