1 回答

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í)例
- 1 回答
- 0 關(guān)注
- 107 瀏覽
添加回答
舉報(bào)