4 ms·
Why can't `if condition { panic(err) }' be used in go as an assert equivalent?
by casparvitch 1y ago
Why can't `if condition { panic(err) }' be used in go as an assert equivalent?
- Jtsummers 1y agoBecause C's assert gets compiled out if you have NDEBUG defined in your program. How do you do conditional compilation in Go (at the level of conditionally including or not including a statement)?
- casparvitch 1y agoAh apologies I misunderstood, thanks
- echoangle 1y ago> How do you do conditional compilation in Go (at the level of conditionally including or not including a statement)? https://stackoverflow.com/questions/36703867/golang-preprocessor-like-c-style-compile-switch https://stackoverflow.com/questions/36703867/golang-preproce... Wouldn't this work? Surely the empty function would be removed completely during compilation?
- Jtsummers 1y agoThat builds or doesn't an entire file. Assert works as a statement. There is not an equivalent in Go to conditionally removing just a statement in a function based on a compile time option.
- echoangle 1y agoCan’t you include or not include a function that contains a single assert, and depending on the condition, the function call is removed or included?
- Jtsummers 1y agoThat defeats the point of asserts. Now you have two copies to keep in sync with each other, whereas asserts are inline with the rest of your code and you have one file that can be built with or without them. They could use a separate tool to produce the assert free version, but that adds tooling beyond what Go provides. Nearly every mainstream language allows you to do this without any extra steps, except Go.