Golang update update by reference value

I call a function to execute an http request, two pass by reference parameters are used for this function. I pass the [] byte to v interface. I want a function to update the v reference value of an interface. The response body is a string, I want to pass a string value to the v-interface. However, I tried many ways, but did not succeed.

Here is the code, you can see that I declare byts as v.(*[]byte) to make v updated string value of the response body. But that does not work. v always nil . Please suggest any way to make v can be updated with a string value.

 func (s *BackendConfiguration) Do(req *http.Request, v interface{}) error { res, err := s.HTTPClient.Do(req) defer res.Body.Close() resBody, err := ioutil.ReadAll(res.Body) if v != nil { byts, ok := v.(*[]byte) if len(resBody) > 0 { byts = append(byts, resBody...) return nil } } } return nil } 
+5
source share
1 answer

Well, the main reason this doesn't work is because you think of β€œlink-by-link,” a concept completely unknown to Go. Everything is called a value in Go, and as soon as you describe what a byte slice is, a pointer to a byte slice, a pointer to a byte fragment wrapped inside an interface, a copy of a pointer to a byte fragment extracted from the interface, etc. You will see how to update the value of the pointer to the byte points of the fragment:

 package main import "fmt" func f(v interface{}) { pbs := v.(*[]byte) *pbs = append(*pbs, []byte{9,8,7}...) } func main() { bs := []byte{1,2,3} pbs := &bs var v interface{} = pbs f(v) fmt.Printf("%v\n", *pbs) } 
+8
source

Source: https://habr.com/ru/post/1213793/


All Articles