bitset: to panic or not to panic, that is the question
New() intercepts a panic in defer() of makeslice and at least for this reason New() is not inlineable and therefore the slice always escapes to the heap. Currently I work around this with From(buffer) but would it also be possible that a MustNew(int) is possibly inlineable if it just propagates the panic.
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Comments: 18 (17 by maintainers)
@lukesandberg
Fundamentally, the call to
Newis allocating and can thus panic.The Len function is trivial:
The New function is effectively just…
The only difference is that we recover on a panic caused by a lack of memory when the
makefunction is called.So the only case that matters is the one where you ask for a slice that Go cannot create.
In that case, instead of doing nothing (which would just cause a panic in your code which you would need to handle), we set the length to zero and use a zero slice.
To be clear, in Go, the following is not guaranteed to work…
If
somelengthis an arbitary value, the call tomakemay fail. This has nothing to do with the library, it is part of the Go language.You can try it out with this program:
It should panic. So the line
fmt.Println(len(x))is never called.Our API can change but it would change the semantics of the code, so we need to make sure that the users are made aware of the change… otherwise we risk creating unexpected bugs in existing code.
@gaissmai
You know this, but for people reading these comments… The code (
b.Set(l).Clear(l)) may panic iflis an arbitrary integer. Thus, in general, if you do not want to have a panic, and you cannot control whatlis, you should have adeferin your code.Sure, pull request invited.