Range references instead values

前端 未结 3 1999
广开言路
广开言路 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:24

    It's been said in the comments already, but for those looking for answers right away, here's how you can achieve expected result by using a slice of pointers and by making the least changes to the original code.

    package main
    
    import "fmt"
    
    type MyType struct {
        field string
    }
    
    func main() {
        // Slice of pointers instead of slice of type
        var array [10]*MyType
    
        // Initialize array manually
        for idx := range array {
            array[idx] = &MyType{}
        }
    
        for _, e := range array {
            e.field = "foo"
        }
    
        for _, e := range array {
            fmt.Println(e.field)
            fmt.Println("--")
        }
    
    }
    

    Here it is in playground

    0 讨论(0)
  • 2020-12-04 23:46
    package main
    
    import "fmt"
    
    type MyType struct {
        field string
    }
    
    func main() {
        var array [10]MyType
    
        for index := range array {
            array[index].field = "foo"
        }
    
        for _, e := range array {
            fmt.Println(e.field)
            fmt.Println("--")
        }
    }
    
    0 讨论(0)
  • 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("--")
        }
    }
    
    0 讨论(0)
提交回复
热议问题