go - The Reader interface change value -
i have question reader interface, definition looks like:
type reader interface { read(p []byte) (n int, err error) }
i have following code use reader interface:
package main import ( "fmt" "os" ) // reading files requires checking calls errors. // helper streamline our error checks below. func check(e error) { if e != nil { panic(e) } } func main() { // you'll want more control on how , // parts of file read. these tasks, start // `open`ing file obtain `os.file` value. f, err := os.open("configuration.ini") check(err) // read bytes beginning of file. // allow 5 read note how many // read. b1 := make([]byte, 10) n1, err := f.read(b1) check(err) fmt.printf("%d bytes: %s\n", n1, string(b1)) f.close() }
as can see code above, b1
defined byte slice , passed read
method value argument. after read
method, b1
contains first 10 letters file.
what me confusing code above is, why b1
contains values after read
method.
in golang, when pass value method, passed value , not reference. clarify, talking about, made 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
not contain values , expected in golang, arguments pass value function or method.
why then, first code snippet can change content of passed argument? if read
method expects pointer of []byte
slice, agreed, on case not.
everything passed value (by creating copy of value being passed).
but since slices in go descriptors contiguous segment of underlying array, descriptor copied refer same underlying array, if modify contents of slice, same underlying array modified.
if modify slice value in function, not reflected @ calling place, because slice value copy , copy modified (not original slice descriptor value).
if pass pointer, value of pointer passed value (the pointer value copied), in case if modify pointed value, same @ calling place (the copy of pointer , original pointer points same object/value).
related blog articles:
Comments
Post a Comment