来自 Goroutine 通道的随机结果,该通道接收指向底层对象的指针

我刚开始学习GO。我正在尝试接收一个对象,但想通过指向底层对象的指针来更新它。但是代码不能正常工作,有人可以告诉我如何修复它吗?


package main


import (

    "encoding/json"

    "fmt"

)


type JSONStr struct {

    str []byte

    err error

}


type person struct {

    First string

    Last  string

    Age   int

}


func test(ch chan *JSONStr) {


    t := <-ch


    p1 := person{

        First: "James",

        Last:  "Bond",

        Age:   32,

    }


    p2 := person{

        First: "Miss",

        Last:  "Moneypenny",

        Age:   27,

    }


    people := []person{p1, p2}

    fmt.Println(people)

    t.str, t.err = json.Marshal(people)

}


func main() {

    ch := make(chan *JSONStr)

    var result JSONStr

    go test(ch)

    ch <- &result

    fmt.Println(result)

}


临摹微笑
浏览 91回答 1
1回答

蓝山帝景

到您 printresult时,它可能还没有被变异test。解决此问题的一种简单方法是通过使用两个通道,如下所示:package mainimport (&nbsp; &nbsp; "encoding/json"&nbsp; &nbsp; "fmt")type JSONStr struct {&nbsp; &nbsp; str []byte&nbsp; &nbsp; err error}func (j JSONStr) String() string {&nbsp; &nbsp; return fmt.Sprintf("str=%s, err=%s", j.str, j.err)}type person struct {&nbsp; &nbsp; First string&nbsp; &nbsp; Last&nbsp; string&nbsp; &nbsp; Age&nbsp; &nbsp;int}func test(in <-chan bool, out chan<- *JSONStr) {&nbsp; &nbsp; <-in&nbsp; &nbsp; people := []person{&nbsp; &nbsp; &nbsp; &nbsp; {First: "James", Last: "Bond", Age: 32},&nbsp; &nbsp; &nbsp; &nbsp; {First: "Miss", Last: "Moneypenny", Age: 27},&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(people)&nbsp; &nbsp; b, err := json.Marshal(people)&nbsp; &nbsp; out <- &JSONStr{str: b, err: err}}func main() {&nbsp; &nbsp; in, out := make(chan bool), make(chan *JSONStr)&nbsp; &nbsp; go test(in, out)&nbsp; &nbsp; in <- true&nbsp; &nbsp; result := <-out&nbsp; &nbsp; fmt.Println(result)}编辑:从函数返回指针在 Go 中是安全且惯用的。从有效围棋:请注意,与 C 不同,返回局部变量的地址是完全可以的;与变量关联的存储在函数返回后仍然存在。事实上,获取复合文字的地址会在每次评估时分配一个新实例
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go