Edd*_*his 13 pointers channel go lang
可以在go lang中将指针传递到通道上吗?我需要传递struct,对其进行更改并在struct传递的相同函数中进行更改?
我试过了
chan <- &data
Run Code Online (Sandbox Code Playgroud)
我得到了
# command-line-arguments .\o.go:130: cannot use &duom[i] (type *KaVartoti) as type KaVartoti in send
Run Code Online (Sandbox Code Playgroud)
在此之后我尝试了
chan <- *data
Run Code Online (Sandbox Code Playgroud)
我得到了
# command-line-arguments .\o.go:130: invalid indirect of duom[i] (type KaVartoti)
Run Code Online (Sandbox Code Playgroud)
那么,可以通过Go中的通道发送指针吗?
nos*_*nos 16
当然可以,例如
package main
type Data struct {
i int
}
func func1(c chan *Data ) {
for {
var t *Data;
t = <-c //receive
t.i += 10 //increment
c <- t //send it back
}
}
func main() {
c := make(chan *Data)
t := Data{10}
go func1(c)
println(t.i)
c <- &t //send a pointer to our t
i := <-c //receive the result
println(i.i)
println(t.i)
}
Run Code Online (Sandbox Code Playgroud)
你得到的错误告诉你你的频道采用了KaVartoti结构,你必须创建一个KaVartoti指针通道(a chan *KaVartoti).
猜测,你的duom变量是一个数组/切片,所以如果你想发送指向其中一个元素的指针,你可以使用你的第一个方法&duom[i]