-2

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\n", 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.

icza
  • 389,944
  • 63
  • 907
  • 827
softshipper
  • 32,463
  • 51
  • 192
  • 400

3 Answers3

3

Everything is passed by value (by creating a copy of the value being passed).

But since slices in Go are just descriptors for a contiguous segment of an underlying array, the descriptor will be copied which will refer to the same underlying array, so if you modify the contents of the slice, the same underlying array is modified.

If you modify the slice value itself in the function, that is not reflected at the calling place, because the slice value is just a copy and the copy will be modified (not the original slice descriptor value).

If you pass a pointer, the value of the pointer is also passed by value (the pointer value will be copied), but in this case if you modify the pointed value, that will be the same as at the calling place (the copy of the pointer and the original pointer points to the same object/value).

Related blog articles:

Go Slices: usage and internals

Arrays, slices (and strings): The mechanics of 'append'

icza
  • 389,944
  • 63
  • 907
  • 827
  • 1
    A slice is exactly not a reference type. It's a value type, which contains a reference to the underlying array. – Paul Hankin Apr 29 '15 at 07:23
  • @Anonymous By _reference_ I don't mean the same as _pointer_. But edited to make it unambigous. Thanks. – icza Apr 29 '15 at 07:26
  • @Anonymous _Reference_ type is not the same as _Pointer_ type. Please check blog article [Go maps in action](http://blog.golang.org/go-maps-in-action): _"Map types are **reference** types, like pointers or **slices**"_ – icza Apr 29 '15 at 07:51
  • 1
    I think it's an error in that article that it describes slices as a reference type. – Paul Hankin Apr 29 '15 at 10:37
1

The slice header in Go contains in itself a pointer to the underlaying array.

You can read from the official blog post: https://blog.golang.org/slices

Even though the slice header is passed by value, the header includes a pointer to elements of an array, so both the original slice header and the copy of the header passed to the function describe the same array. Therefore, when the function returns, the modified elements can be seen through the original slice variable.

ANisus
  • 74,460
  • 29
  • 162
  • 158
0

It is the exact same behaviour as passing a pointer in C :

#include <stdio.h>
#include <stdlib.h>

// p is passed by value ; however, this function does not modify p,
// it modifies the values pointed by p.
void read(int* p) {
    int i;
    for( i=0; i<10; i++) {
        p[i] = i+1;
    }
}

// p is passed by value, so changing p itself has no effect out
// of the function's scope
void passAsValue(int*p) {
   int* c = (int*)malloc(3*sizeof(int));

   c[0] = 15; // 'F' in hex is 15 ...
   c[1] = 0;
   c[2] = 0;

   p = c;
}

int main() {
    int* p = (int*)malloc(10*sizeof(int));
    int i;
    for( i=0; i<10; i++) {
        p[i] = 0;
    }

    printf("             init : p[0] = %d\n", p[0]);

    read(p);
    printf("       after read : p[0] = %d\n", p[0]);

    passAsValue(p);
    printf("after passAsValue : p[0] = %d\n", p[0]);

    return 0;
}

output :

//             init : p[0] = 0
//       after read : p[0] = 1
//after passAsValue : p[0] = 1 // <- not 15, the modification from
//                             //    within passAsValue is not persistent

(for the record : this C program leaks the int* c array)

A Go slice contains more info than just the pointer : it is a small struct, which contains the pointer, the length, and the max capacity of the allocated array (see the link mentioned in other answers : https://blog.golang.org/slices ).
But from the code's perspective, it behaves exactly like the C pointer.

LeGEC
  • 46,477
  • 5
  • 57
  • 104