Passed By Value or Reference

Simple definitions :

Passed by value : Passing a copy of the value to somebody , when the copied value being changed , nothing is changed to the original.

Passed by reference : Passing a copy of the address of the value to somebody , when the value being changed , original value changed.

What are their roles in Golang ?

For example, passing an int value to a function makes a copy of the int, and passing a pointer value makes a copy of the pointer, but not the data it points to.

package main

package main

import "fmt"

func increaseOne(v int) int {
    v = v + 1
    return v
}

func main() {
    u := 2
    w := increaseOne(u)         // passing an int to a function
    fmt.Println("u =", u)
    fmt.Println("w =", w)
}

[output]
u = 2
w = 3

Map and slice values behave like pointers: they are descriptors that contain pointers to the underlying map or slice data. Copying a map or slice value doesn't copy the data it points to.

Copying an interface value makes a copy of the thing stored in the interface value. If the interface value holds a struct, copying the interface value makes a copy of the struct. If the interface value holds a pointer, copying the interface value makes a copy of the pointer, but again not the data it points to.

Examples

[TODO]

results matching ""

    No results matching ""