如何遍历通道并指定为参考

时间:2018-10-02 01:16:43

标签: go channel

似乎将通道输出分配给指针数组将始终分配发送到通道<html>的最后一个指针。谁能解释这种行为?

string2

导致:

package main

import (
    "fmt"
)

type myType struct {
    myString string
}

func main() {
    queue := make(chan myType, 2)
    queue <- myType{myString: "string1"}
    queue <- myType{myString: "string2"}
    close(queue)

    var types []*myType

    for element := range queue {
        types = append(types, &element)
    }

    for _, element := range types {
        fmt.Println(element.myString)
    }
}

1 个答案:

答案 0 :(得分:2)

这与渠道无关。检查以下具有相同结果的代码:

package main

import (
    "fmt"
)

type myType struct {
    myString string
}

func main() {
    in := [2]myType{
        myType{myString: "string1"},
        myType{myString: "string2"},
    }

    var types []*myType

    for _, element := range in {
        types = append(types, &element)
    }

    for _, element := range types {
        fmt.Println(element.myString)
    }
}

Play

问题是您要指向element,这是一个每次循环都会获得新值的变量var types []myType for element := range queue { types = append(types, element) } ,但是变量本身保持不变,因此您附加到切片的所有指针都指向相同的值。要解决此问题,请在循环中附加值而不是指针,或在循环中创建一个临时对象,然后将指针推送到临时对象

var types []*myType

for element := range queue {
    tmp := element
    types = append(types, &tmp)
}

createStore