Home > Article > Backend Development > Go vet reports "Possible misuse of reflect.SliceHeader"
php editor Zimo brings you news about the Go vet report today. Recently, the Go language official issued a warning stating that there may be abuse of reflect.SliceHeader. Go vet is a static analysis tool in the Go language, used to check common errors and potential problems in the code. The report advises developers to be careful when using reflect.SliceHeader to avoid potential problems. In this article, we will explain this problem in detail and provide corresponding solutions.
I have the following code snippet and "go vet" complains about the warning "Possible misuse of reflect.sliceheader". I can't find any more information about this warning other than this. After reading this I'm not quite sure what needs to be done to make go vet happy - and not have possible gc issues.
The goal of this code snippet is to have the go function copy data into memory managed by the opaque c library. The go function requires a []byte as parameter.
func Callback(ptr unsafe.Pointer, buffer unsafe.Pointer, size C.longlong) C.longlong { ... sh := &reflect.SliceHeader{ Data: uintptr(buffer), Len: int(size), Cap: int(size), } buf := *(*[]byte)(unsafe.Pointer(sh)) err := CopyToSlice(buf) if err != nil { log.Fatal("failed to copy to slice") } ... }
It looks like jimb (from the comments) hinted at the most correct answer, although he didn't post it as an answer or include an example. The following passes vet, staticcheck and golangci-lint - and doesn't segfault, so I think this is the correct answer.
func Callback(ptr unsafe.Pointer, buffer unsafe.Pointer, size C.longlong) C.longlong { ... buf := unsafe.Slice((*byte)(buffer), size) err := CopyToSlice(buf) if err != nil { log.Fatal("failed to copy to slice") } ... }
The above is the detailed content of Go vet reports "Possible misuse of reflect.SliceHeader". For more information, please follow other related articles on the PHP Chinese website!