douyuan1049 2017-08-02 18:08
浏览 31
已采纳

切片结构与指向结构的指针

I don't understand the behavior of the following piece of code. In creating a list of matching structs as a slice of struct pointers, the code always prints the last element of original array (which actually wasn't a match)—it prints 12 and 12. However, if I change matches to be []Widget instead of []*Widget, then it will print 10 and 11.

Why is this?

package main

import (
    "fmt"
)

func main() {

    type Widget struct {
        id    int
        attrs []string
    }

    widgets := []Widget{
        Widget{
            id:    10,
            attrs: []string{"blah", "foo"},
        },
        Widget{
            id:    11,
            attrs: []string{"foo", "bar"},
        },
        Widget{
            id:    12,
            attrs: []string{"xyz"},
        },
    }

    var matches []*Widget
    for _, w := range widgets {
        for _, a := range w.attrs {
            if a == "foo" {
                matches = append(matches, &w)
                break
            }
        }
    }

    for _, m := range matches {
        fmt.Println(m.id)
    }

}
  • 写回答

1条回答 默认 最新

  • dtzhfb4869 2017-08-02 18:18
    关注

    That's because when you use the pointers you are adding &w to the array.

    Note that w is actually the local variable used in the loop, so that's not the address you want to add to the matches array.

    (even though the value of the variable w changes through the loop, it's address stays the same)

    When the loop ends, w ends up with the last value so that's why it prints 12 two times.

    You need to add the address of the element that matched instead.

    If you do this:

    matches = append(matches, &widgets[i])
    

    Then it'd work fine with pointers as well.

    Modified Go playground for you to test it:

    https://play.golang.org/p/YE-cokyEHu

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?