可以在Go lang中将指针传递到通道上吗?我需要传递struct,对其进行更改,并在传递struct的同一函数中进行这些更改?

我试过了

chan <- &data

然后我就得到了

# command-line-arguments .\o.go:130: cannot use &duom[i] (type *KaVartoti) as type KaVartoti in send

after this 我试过了

chan <- *data

然后我就得到了

# command-line-arguments .\o.go:130: invalid indirect of duom[i] (type KaVartoti)

那么,在GO IR中通过通道发送指针是可能的,不是吗?

推荐答案

当然可以.

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)
}

请参见Go Playground中的.

您得到的错误告诉您,您的通道采用KaVartoti struct ,您必须创建一个KaVartoti指针的通道(chan *KaVartoti).

根据猜测,您的duom变量是一个数组/片,所以如果您想要发送一个指向其中一个元素的指针,您将使用第一种方法&duom[i]

Go相关问答推荐

Golang regexpp:获取带有右括号的单词

如何创建两个连接的io.ReadWriteClosers以用于测试目的

Go协议缓冲区导入问题

Golang测试容器,无法使网络正常工作

使用GO从RDPMC获得价值

错误&对象已被Golang在K8s操作符上修改

无法使用exec从管道中读取.Go中的命令

go aws-lambda 与 terraform 中的 exec 格式错误

从带有嵌套括号的字符串中提取值

在 Go 中解组编号的 XML 标签

使用 httptest 对 http 请求进行单元测试重试

用于提取 <*n 的正则表达式(其中 n 是一个数字)

从 eBPF LRU 哈希映射中错误驱逐的元素

是否可以从 golang 中的参数推断类型?

使用 AppID 在 Windows 中启动应用程序并获取 pid

如何在循环中旋转图像以便在 golang 中创建 GIF?

使用 bolthold 3 条件进行 boltDB 查询

如何使用带有Electron 表格 ID、Electron 表格名称、表格 ID 和值的 golang 在 googlesheet 中插入数据

传递上下文的最佳方式

Gin中测试模式有什么用