3 ms·
If out of bounds errors were undefined behavior, lifting the bounds check out of the loop would be legal. But in go, it isn't an error. It is equivalent to pani
by kevhito 10y ago
If out of bounds errors were undefined behavior, lifting the bounds check out of the loop would be legal. But in go, it isn't an error. It is equivalent to panic(), which can be caught. If the caller recovers, they should see the partially-completed loop, but lifting it out of the loop would change that behavior.
Here is an example, using your copy function:
https://play.golang.org/p/Cc3Oc3le-9 https://play.golang.org/p/Cc3Oc3le-9
- kbenson 10y agoI think the point is that in the cases where you can prove it's not possible, you can optimize it out. This is functionally the same, because if it's incapable of panicing because of out of bounds, you don't need to check for it. I think what you likely get in practice is something like: func copy(src []int, dst []int) { if (len(src) <= len(dst) { for i := range(src) { dst[i] = src[i] } else { for i := range(src) { assert(i < len(dst)) // subscript check dst[i] = src[i] } } } That way you still get panics in the case where they are applicable, but not in the cases where you can safely abstract the bounds check away (because a panic for that reason should not be possible). Although this is likely at the code generation level, so you can consider the if statement to be a sort of macro branching on what code is actually generated.
- Animats 10y agoGo backed into exceptions. Originally, "panic" was always fatal.[1] Then came "recover".[2] But it was considered bad form to use "recover" for anything other than doing a final cleanup and exit. Now, the library JSON parser can panic and recover due to invalid input, then return an error code. That's exception handling. Now we have to give up optimizations so that Go's exception handling will work. Every function call, every subscripted access, and every map reference is a potential loop exit. Bleah. [1] http://dave.cheney.net/2012/01/18/why-go-gets-exceptions-right http://dave.cheney.net/2012/01/18/why-go-gets-exceptions-rig... [2] https://groups.google.com/forum/#!topic/golang-nuts/HOXNBQu5c-Q%5B1-25%5D https://groups.google.com/forum/#!topic/golang-nuts/HOXNBQu5...