范围引用而不是值 [英] Range references instead values

查看:28
本文介绍了范围引用而不是值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到该范围返回键和副本"的价值.该范围有没有办法返回项目的地址?示例

I saw that range returns the key and the "copy" of the value. Is there a way for that range to return the adress of the item? Example

package main

import "fmt"

type MyType struct {
    field string
}

func main() {
    var array [10]MyType

    for _, e := range array {
        e.field = "foo"
    }

    for _, e := range array {
        fmt.Println(e.field)
        fmt.Println("--")
    }
}

http://play.golang.org/p/AFOGG9NGpx

这里是字段"未修改,因为范围发送字段的副本,我必须使用索引还是有其他方法可以修改值?

Here "field" is not modified because range sends the copy of field, Do I have to use index or is there any other way to modify the value?

推荐答案

The short &直接回答:不,使用数组索引代替值

The short & direct answer: no, use the array index instead of the value

所以上面的代码变成:

package main

import "fmt"

type MyType struct {
    field string
}

func main() {
    var array [10]MyType

    for idx, _ := range array {
        array[idx].field = "foo"
    }

    for _, e := range array {
        fmt.Println(e.field)
        fmt.Println("--")
    }
}

这篇关于范围引用而不是值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆