doucha5080 2010-06-20 13:46
浏览 43
已采纳

对于结构顶点,map [int] vertex和map [int] * vertex有什么区别?

To define a map from int to struct vertex, should I define map[int]vertex or map[int]*vertex? Which one is preferred?

I extended Chickencha's 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)
}

The output:

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

From the output, my understanding is, if I want to change the struct member in place, I must use pointer to the struct. But I'm still not sure the underlying reasons. Especially, why I cannot assign to a[0].x?

  • 写回答

2条回答 默认 最新

  • dongwolu5275 2010-06-20 21:22
    关注

    The main difference is that map[int]vertex stores vertex values and map[int]*vertex stores vertex references (pointers). The output 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)
    }
    

    Output:

    0 0 4 4
    

    The vertex stored in b is modified by the v.x, v.y = 4, 4 line, while the vertex stored in a is not.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?