dousi1994 2018-07-12 13:42
浏览 34
已采纳

切片指针和循环[重复]

This question already has an answer here:

I think this question where asked several times but I still confused:

I have following code:

type obj struct {
    s *string
}

var cmdsP = []*string {
    stringPointer("create"),
    stringPointer("delete"),
    stringPointer("update"),
}

var cmds = []string {
    "create",
    "delete",
    "update",
}

// []*string
func loop1() {
    slice := make([]obj, 0, 0)

    for _, cmd := range cmdsP {
        slice = append(slice, obj{cmd})
    }
    for _, o := range slice {
        fmt.Println(*o.s)
    }
}

// []string
func loop2() {
    slice := make([]obj, 0, 0)
    for _, cmd := range cmds {
        slice = append(slice, obj{&cmd})
    }
    for _, o := range slice {
        fmt.Println(*o.s)
    }
}

func stringPointer(v string) *string {
    return &v
}

https://play.golang.org/p/65Le_8Pi3Mi

The only difference is in slice semantic []*string and []string how does it change behavior of cmd variable? Could you please draw or explain in details what happens in memory during iteration through two loops?

</div>
  • 写回答

2条回答 默认 最新

  • douqiao8370 2018-07-12 13:48
    关注

    When you call range on a collection, the go runtime initialises 2 memory locations; one for the index (in this case _), and one for the value cmd.

    What range then does, is take each of the items in the collection and copy them into the memory location that it created when you called range.

    This means that each of the items in the slice get put into that memory location one by one.

    When you do &cmd you are taking a pointer. This pointer points to the shared memory location that each of the slice items are being copied into.

    All of your pointers created using &cmd all point to the same memory location.

    This means that after the range is done, the only value left in that memory location that your pointers are pointing to is the last value from the range iteration.

    This is why you get the output

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

报告相同问题?