Golang更新通过引用传递的值

huangapple go评论83阅读模式
英文:

Golang update pass by reference value

问题

我正在调用一个函数来执行 HTTP 请求,该函数使用两个按引用传递的参数。我将 []byte 传递给 v 接口。我希望函数能够更新 v 接口的引用值。响应体是一个字符串,我想将字符串值传递给 v 接口。然而,尝试了很多方法都没有成功。

以下是代码,你可以看到我在声明中将 byts 声明为 v.(*[]byte),以便使 v 更新为响应体的字符串值。但它不起作用。v 总是 nil。请建议任何方法,使 v 可以更新为字符串值。

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
}
英文:

I am calling a function to do a http request, two pass by reference parameter is used for the function. I pass the []byte to v interface. I want the function to update the v interface reference value. The response body is a string, I want to pass the string value to v interface. However, tried many ways but not success.

Here is the code, you can see I declare byts as v.(*[]byte) in order to make v updated with the string value of response body. But it does not work. The v is always nil. Please suggest any way to make v can be updated with the 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
}

答案1

得分: 10

这段代码无法正常工作的主要原因是因为你在考虑"按引用调用"的概念,而这在Go语言中是完全不被支持的。在Go语言中,一切都是按值传递的,一旦你明确了什么是字节切片、字节切片的指针、包装在接口中的字节切片的指针、从接口中提取的字节切片指针的副本等等,你就会明白如何更新指向字节切片的指针所指向的值。

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)
}
英文:

Well, the main reason this does not work is because you think of "call by reference", a concept completely unknown to Go. Absolutely everything is called by value in Go and once you spell out what is a byte slice, a pointer to a byte slice, a pointer to byte slice wrapped inside an interface, a copy of the pointer to a byte slice extracted from the interface, and so on you'll see how to update the value the pointer to byte slice points to:

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)
}

huangapple
  • 本文由 发表于 2015年2月20日 18:07:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/28626312.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定