I have a question about the reader interface, the definition looks like:
type Reader interface {
Read(p []byte) (n int, err error)
}
I have following code that use the reader interface:
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
", n1, string(b1))
f.Close()
}
As you can see the code above, b1
is defined as byte slice and it passed to the Read
method as value argument. After the Read
method, the b1
contains the first 10 letters from file.
What for me very confusing about the code above is, why does b1
contains suddenly values after the Read
method.
In Golang, when I pass a value to the method, it will be passed as value and not as reference. To clarify, what I talking about, I made a sample application:
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))
}
After passAsValue
function, b
does not contain any values and that what I expected in golang, arguments will be pass as value to the function or method.
Why then, the first code snippet can change the content of the passed argument? If the Read
method expects a pointer of []byte
slice, then I would be agreed, but on this case not.