AmitKumarDas / fun-with-programming

ABC - Always Be Coding
2 stars 2 forks source link

[go] maps & channels are not references #9

Closed AmitKumarDas closed 2 years ago

AmitKumarDas commented 3 years ago

refer

// go does not have reference variables
// there is no pass-by-reference in go
// there is no pass-by-reference function semantics
// what is reference
// it is an alias to a variable
// it is an alternate name to a variable
// alias == alternate == reference variable
// every variable defined in go occupies a unique memory location
#include <stdio.h>

// this works in c++
int main() {
        int a = 10;
        int &b = a;
        int &c = b;

        // 0x7ffe114f0b14 0x7ffe114f0b14 0x7ffe114f0b14
        printf("%p %p %p\n", &a, &b, &c); 
        return 0;
}
// It is not possible to create a Go program 
// where two variables share the same storage location in memory.
//
// It is possible to create two variables 
// whose contents point to the same storage location, 
// but that is not the same thing as 
// two variables who share the same storage location.

func main() {
        var a int
        var b, c = &a, &a
        fmt.Println(b, c)   // 0x1040a124 0x1040a124
        fmt.Println(&b, &c) // 0x1040c108 0x1040c110

        // updating contents of b will not impact c's contents [f5]
}
AmitKumarDas commented 3 years ago
func fn(m map[int]int) {
        m = make(map[int]int)
}

func main() {
        var m map[int]int
        fn(m)
        fmt.Println(m == nil) // true
}
AmitKumarDas commented 3 years ago

refer

// map is not a reference variable
// map is a pointer to runtime.hmap structure
// a map value is the same size as a uintptr–one machine word
func main() {
    var m map[int]int
    var p uintptr
    fmt.Println(unsafe.Sizeof(m), unsafe.Sizeof(p)) // 8 8 (linux/amd64)
}
// map like channels are pointers to runtime types
// slice is not