【发布时间】:2015-07-08 07:46:18
【问题描述】:
我有一个关于阅读器界面的问题,定义如下:
type Reader interface {
Read(p []byte) (n int, err error)
}
我有以下使用阅读器界面的代码:
package main
import (
"fmt"
"os"
)
// Reading files requires checking most calls for errors.
// This helper will streamline our error checks below.
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
// You'll often want more control over how and what
// parts of a file are read. For these tasks, start
// by `Open`ing a file to obtain an `os.File` value.
f, err := os.Open("configuration.ini")
check(err)
// Read some bytes from the beginning of the file.
// Allow up to 5 to be read but also note how many
// actually were read.
b1 := make([]byte, 10)
n1, err := f.Read(b1)
check(err)
fmt.Printf("%d bytes: %s\n", n1, string(b1))
f.Close()
}
正如您在上面的代码中看到的,b1 被定义为字节切片,并作为值参数传递给Read 方法。在 Read 方法之后,b1 包含文件中的前 10 个字母。
我对上面的代码非常困惑的是,为什么b1 在Read 方法之后突然包含值。
在 Golang 中,当我将值传递给方法时,它将作为值而不是作为引用传递。为了澄清,我在说什么,我做了一个示例应用程序:
package main
import (
"fmt"
)
func passAsValue(p []byte) {
c := []byte("Foo")
p = c
}
func main() {
b := make([]byte, 10)
passAsValue(b)
fmt.Println(string(b))
}
在passAsValue 函数之后,b 不包含任何值,并且我在 golang 中所期望的,参数将作为值传递给函数或方法。
那为什么第一个代码 sn -p 可以改变传递参数的内容呢?如果Read 方法需要[]byte 切片的指针,那么我会同意,但在这种情况下不是。
【问题讨论】: