亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

來自 Goroutine 通道的隨機結果,該通道接收指向底層對象的指針

來自 Goroutine 通道的隨機結果,該通道接收指向底層對象的指針

Go
臨摹微笑 2022-06-13 15:56:23
我剛開始學習GO。我正在嘗試接收一個對象,但想通過指向底層對象的指針來更新它。但是代碼不能正常工作,有人可以告訴我如何修復它嗎?package mainimport (    "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)}
查看完整描述

1 回答

?
藍山帝景

TA貢獻1843條經驗 獲得超7個贊

到您 printresult時,它可能還沒有被變異test。解決此問題的一種簡單方法是通過使用兩個通道,如下所示:


package main


import (

    "encoding/json"

    "fmt"

)


type JSONStr struct {

    str []byte

    err error

}


func (j JSONStr) String() string {

    return fmt.Sprintf("str=%s, err=%s", j.str, j.err)

}


type person struct {

    First string

    Last  string

    Age   int

}


func test(in <-chan bool, out chan<- *JSONStr) {

    <-in


    people := []person{

        {First: "James", Last: "Bond", Age: 32},

        {First: "Miss", Last: "Moneypenny", Age: 27},

    }

    fmt.Println(people)


    b, err := json.Marshal(people)

    out <- &JSONStr{str: b, err: err}

}


func main() {

    in, out := make(chan bool), make(chan *JSONStr)

    go test(in, out)

    in <- true

    result := <-out

    fmt.Println(result)

}

編輯:從函數返回指針在 Go 中是安全且慣用的。從有效圍棋:


請注意,與 C 不同,返回局部變量的地址是完全可以的;與變量關聯的存儲在函數返回后仍然存在。事實上,獲取復合文字的地址會在每次評估時分配一個新實例


查看完整回答
反對 回復 2022-06-13
  • 1 回答
  • 0 關注
  • 109 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號