第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

來自 Goroutine 通道的隨機(jī)結(jié)果,該通道接收指向底層對(duì)象的指針

來自 Goroutine 通道的隨機(jī)結(jié)果,該通道接收指向底層對(duì)象的指針

Go
臨摹微笑 2022-06-13 15:56:23
我剛開始學(xué)習(xí)GO。我正在嘗試接收一個(gè)對(duì)象,但想通過指向底層對(duì)象的指針來更新它。但是代碼不能正常工作,有人可以告訴我如何修復(fù)它嗎?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 回答

?
藍(lán)山帝景

TA貢獻(xiàn)1843條經(jīng)驗(yàn) 獲得超7個(gè)贊

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


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)

}

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


請(qǐng)注意,與 C 不同,返回局部變量的地址是完全可以的;與變量關(guān)聯(lián)的存儲(chǔ)在函數(shù)返回后仍然存在。事實(shí)上,獲取復(fù)合文字的地址會(huì)在每次評(píng)估時(shí)分配一個(gè)新實(shí)例


查看完整回答
反對(duì) 回復(fù) 2022-06-13
  • 1 回答
  • 0 關(guān)注
  • 107 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)