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

似乎将 channel 输出分配给一个指针数组将始终分配最后一个发送到 channel 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)

    }

}

结果是:


result2

result2


繁星点点滴滴
浏览 80回答 1
1回答

红糖糍粑

这与渠道无关。检查具有相同结果的代码:package mainimport (&nbsp; &nbsp; "fmt")type myType struct {&nbsp; &nbsp; myString string}func main() {&nbsp; &nbsp; in := [2]myType{&nbsp; &nbsp; &nbsp; &nbsp; myType{myString: "string1"},&nbsp; &nbsp; &nbsp; &nbsp; myType{myString: "string2"},&nbsp; &nbsp; }&nbsp; &nbsp; var types []*myType&nbsp; &nbsp; for _, element := range in {&nbsp; &nbsp; &nbsp; &nbsp; types = append(types, &element)&nbsp; &nbsp; }&nbsp; &nbsp; for _, element := range types {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(element.myString)&nbsp; &nbsp; }}玩问题是您正在使用一个指向变量的指针element,该变量每次循环都会获得一个新值,但变量本身保持不变,因此您附加到切片的所有指针都指向相同的值。要解决此问题,请附加值而不是指针,或者在循环中创建一个临时变量并将指针推送到临时变量var types []myTypefor element := range queue {&nbsp; &nbsp; types = append(types, element)}或者var types []*myTypefor element := range queue {&nbsp; &nbsp; tmp := element&nbsp; &nbsp; types = append(types, &tmp)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go