golang - slices, channel, map, pointers are references types - others are considered value type

When working with golang, it is important to remember that slices, channel, pointers and map are references types. The rest like string, integer are considered be value type. Example of code that demonstrate this here. You can see that although I am passing a struct into a function, it is a value type instead of reference type. 


package main

import "fmt"

type Emplyee struct {
    name string
    id   int
}

func SetReferenceType(value Emplyee) {
    value.id = 1000
    value.name = "removed"
}

func SetValueType(value int) {
    value = 1000
}

func SetSlicesValue(lst []int) {

    lst[0] = 9
    lst[1] = 10

}

// reftype jeremy 10
// idx 10
// 9
// 10
// 3

func main() {

    e := Emplyee{id: 10, name: "jeremy"}
    SetReferenceType(e)
    fmt.Println("reftype", e.name, e.id)
    // reftype jeremy 10

    idx := 10
    SetValueType(idx)
    fmt.Println("idx", idx)
    // idx 10
    lst := []int{1, 2, 3}

    SetSlicesValue(lst)

    for _, v := range lst {
        fmt.Println(v)
    }

    // 9
    // 10
    // 3
}









Comments

Popular posts from this blog

The specified initialization vector (IV) does not match the block size for this algorithm

NodeJS: Error: spawn EINVAL in window for node version 20.20 and 18.20