For the top of the structure, what is the difference between the top of map [int] and map [int] * vertex?

To define a map from int to struct vertex, should i define map[int]vertexor map[int]*vertex? Which one is preferable?

I expanded the Chickencha code:

package main

type vertex struct {
    x, y int 
}

func main() {
    a := make(map[int]vertex)
    b := make(map[int]*vertex)

    v := &vertex{0, 0}
    a[0] = *v
    b[0] = v 

    v.x, v.y = 4, 4
    println(a[0].x, a[0].y, b[0].x, b[0].y)

    //a[0].x = 3 // cannot assign to (a[0]).x
    //a[0].y = 3 // cannot assign to (a[0]).y
    b[0].x = 3 
    b[0].y = 3 
    println(a[0].x, a[0].y, b[0].x, b[0].y)

    u1 := a[0]
    u1.x = 2 
    u1.y = 2 
    u2 := b[0]
    u2.x = 2 
    u2.y = 2 
    println(a[0].x, a[0].y, b[0].x, b[0].y)
}

Output:

0 0 4 4
0 0 3 3
0 0 2 2

From the output, I understand that if I want to change the structure member in place, I should use a pointer to the structure. But I'm still not sure of the underlying reasons. Especially, why can't I assign [0] .x?

+3
source share
2 answers

The main difference is that it map[int]vertexstores the values ​​of the vertices, and map[int]*vertexstores the links of the vertices (pointers). The result of the following program should help illustrate:

package main

type vertex struct {
    x, y int
}

func main() {
    a := make(map[int]vertex)
    b := make(map[int]*vertex)

    v := &vertex{0, 0}
    a[0] = *v
    b[0] = v

    v.x, v.y = 4, 4
    println(a[0].x, a[0].y, b[0].x, b[0].y)
}

Conclusion:

0 0 4 4

, b, v.x, v.y = 4, 4, , a, .

+2

, , , Go. Go map, hashmap.h hashmap.c, . , , . , ..

, , , .

package main

type vertex struct {
    x, y int
}

func main() {
    a := make(map[int]vertex)
    a[0] = vertex{0, 0}

    println(a[0].x, a[0].y)
    v0 := a[0]
    v0.x = 1
    a[0] = v0
    println(a[0].x, a[0].y)
}

:

0 0
1 0
+1

Source: https://habr.com/ru/post/1750903/


All Articles