Range references instead values

前端 未结 3 1998
广开言路
广开言路 2020-12-04 22:54

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          


        
3条回答
  •  一个人的身影
    2020-12-04 23:47

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

    So the above code becomes:

    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("--")
        }
    }
    

提交回复
热议问题