范围引用代替值 [英] Range references instead values

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

问题描述

我看到该范围返回键和值的副本".有没有办法让该范围返回该商品的地址?例子

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 & 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天全站免登陆