Pointer
pointer is returned by new
A debug experience on pointer in Go.
strategies := new(Config) //new return a pointer to type Config
- err = json.Unmarshal([]byte(strategyJsonStr), &strategies)
+ err = json.Unmarshal([]byte(strategyJsonStr), strategies)
- return &strategies, nil
+ return *strategies, nil
}
- strategies := new(Config)
+ var strategies Config
err = json.Unmarshal([]byte(strategyJsonStr), &strategies)
- return &strategies, nil
+ return strategies, nil
This is a segment of code in ingress-nginx project, json.Unmarshal() need a pointer argument, the old code use &strategies which seems is fine.
But When run e2e tests it failed.
[eric@localhost ingress-nginx]$ PKG="k8s.io/ingress-nginx/internal/ingress/annotations/servicematch" ./build/test.sh
=== RUN TestIngressAnnotationServiceMatchCookie
--- FAIL: TestIngressAnnotationServiceMatchCookie (0.00s)
main_test.go:75: expected a Config type
main_test.go:76: expected a Config got %!s(**servicematch.Config=0xc420078118)
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
Simple debug code can be added as below:
< //t.Errorf("expected a Config got %T", cfg)
< //t.Errorf("expected a Config got %s", cfg)