nilaway
nilaway copied to clipboard
NilAway does't report uninitialized object
It's common to for code like this in Go
package somepackage
import (
"context"
)
type OrderRequest struct {
OrderID string
}
type OrderObserver interface {
ObserveOrder(ctx context.Context, req *OrderRequest) error
}
type AgentSelector struct {
observer OrderObserver
}
func NewAgentSelector() *AgentSelector {
return &AgentSelector{}
}
func (s *AgentSelector) Handle(ctx context.Context, req *OrderRequest) error {
return s.observer.ObserveOrder(ctx, req) // observer is nil, not initialized
}
would be great if NilAway report the potential nil on above snippet
Right! We have a feature named "struct initialization" that handles such cases. It's currently disabled a hidden, but you can enable it via adding <nilaway struct enable>
to the file docstring:
//<nilaway struct enable>
package somepackage
Then, you can add a main function that initializes the AgentSelector
object:
func main() {
a := NewAgentSelector()
a.Handle(context.Background(), nil)
}
Then NilAway complains about such error:
/Users/yuxinw/Uber/nilaway/build/test-repo/main.go:25:9: error: Potential nil panic detected. Observed nil flow from source to dereference point:
-> test-repo/main.go:21:9: uninitialized field `observer` returned by result 0 of `NewAgentSelector()`
-> test-repo/main.go:30:3: field `observer` of result 0 of `NewAgentSelector()` field `observer` of method receiver `s`
-> test-repo/main.go:25:9: field `observer` called `ObserveOrder()`
Note that we put this under a feature flag because this is still experimental (well, NilAway itself should be considered experimental, but this feature is even more experimental), and it brings some amount of performance penalty and false positives. We are evaluating internally as well on making such feature enabled by default :) stay tuned!
great, can't wait until the structinit
enable by default
An additional benefit to these changes is that it is very important to check whether the structure has been initialized.
+1