在Go语言中通过通道传递指针。

huangapple go评论96阅读模式
英文:

Passing pointer through channel in Go Lang

问题

在Go语言中,可以通过通道传递指针吗?我需要传递结构体,并对其进行更改,然后在传递结构体的同一个函数中获取这些更改。

我尝试了以下代码:

chan <- &data

但是我得到了以下错误:

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

之后,我尝试了以下代码:

chan <- *data

但是我得到了以下错误:

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

所以,在Go语言中是否可以通过通道发送指针呢?

英文:

It is possible to pass pointer over channel in go lang? I need to pass struct, do changes in it and have theese changes in the same function from where struct was passed?

I tried

chan &lt;- &amp;data

and I got

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

after this I tried

chan &lt;- *data

and I got

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

So, it is possible to send pointer through channel in Go ir not?

答案1

得分: 23

当然可以,例如:

package main

type Data struct {
    i int
}

func func1(c chan *Data ) {
    for {
        var t *Data;
        t = <-c //接收
        t.i += 10 //增加
        c <- t   //发送回去
    }
}

func main() {
    c := make(chan *Data)
    t := Data{10}
    go func1(c)
    println(t.i)
    c <- &t //发送指向t的指针
    i := <-c //接收结果
    println(i.i)
    println(t.i)
}

Go Playground中查看。

你得到的错误告诉你,你的通道接收的是一个KaVartoti结构体,你需要创建一个KaVartoti指针的通道(chan *KaVartoti)。

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

英文:

Sure you can, e.g.

package main

type Data struct {
    i int
}

func func1(c chan *Data ) {
    for {
        var t *Data;
        t = &lt;-c //receive
        t.i += 10 //increment
        c &lt;- t   //send it back
    }
}

func main() {
    c := make(chan *Data)
    t := Data{10}
    go func1(c)
    println(t.i)
    c &lt;- &amp;t //send a pointer to our t
    i := &lt;-c //receive the result
    println(i.i)
    println(t.i)
}

See in Go Playground.

The error you get tells you that your channel takes a KaVartoti struct, you'll have to create a channel of KaVartoti pointers (a chan *KaVartoti).

At a guess, your duom variable is an array/slice, so if you want to send a pointer to one of the elements, you'd use your first approach of &amp;duom[i]

答案2

得分: -3

请检查以下示例:

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"sync"
)

type weburl struct {
	url string
}

type responseweburl struct {
	contents, index string
}

var urlmap = make(map[string]weburl)

func callurl(ch chan *responseweburl, index, url string, wg *sync.WaitGroup) {
	defer wg.Done()
	response, err := http.Get(url)
	if err != nil {
		fmt.Printf("%s", err)
		os.Exit(1)
	} else {
		defer response.Body.Close()
		contents, err := ioutil.ReadAll(response.Body)
		if err != nil {
			fmt.Printf("%s", err)
			os.Exit(1)
		}
		var responsedata = responseweburl{string(contents), string(index)}
		ch <- responsedata
	}
}

func main() {
	urlmap["google"] = weburl{"http://www.google.com"}
	urlmap["facebook"] = weburl{"http://www.facebook.com"}
	urlmap["linkedin"] = weburl{"http://www.linkedin.com"}
	ch := make(chan *responseweburl)
	var wg sync.WaitGroup
	for index, _ := range urlmap {
		fmt.Println("call url " + index)
		wg.Add(1)
		go callurl(ch, index, urlmap[index].url, &wg)
	}
	wg.Wait()
}

这是一个使用Go语言编写的示例代码。它定义了weburlresponseweburl两个结构体类型,分别表示网址和响应数据。代码中创建了一个urlmap映射,存储了三个网址。callurl函数用于发送HTTP请求并获取响应数据,使用goroutine并发调用多个网址。最后,使用sync.WaitGroup等待所有goroutine执行完毕。

请注意,代码中使用了一些Go语言的标准库,如fmtio/ioutilnet/httpsync

英文:

Check Following Example:

package main
type weburl struct {
url string
}
type responseweburl struct {
contents, index string
}
var urlmap = make(map[string]weburl)
func callurl(ch chan *responseweburl, index, url string, wg *sync.WaitGroup) {
defer wg.Done()
response, err := http.Get(url)
if err != nil {
fmt.Printf(&quot;%s&quot;, err)
os.Exit(1)
} else {
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Printf(&quot;%s&quot;, err)
os.Exit(1)
}
var responsedata = responseweburl{string(contents), string(index)}
ch &lt;- responsedata
}
}
func main(){
urlmap[&quot;google&quot;] = weburl{&quot;http://www.google.com&quot;}
urlmap[&quot;facebook&quot;] = weburl{&quot;http://www.facebook.com&quot;}
urlmap[&quot;linkedin&quot;] = weburl{&quot;http://www.linkedin.com&quot;}
ch := make(chan *responseweburl)
for index, _ := range urlmap {
fmt.Println(&quot;call url &quot; + index)
go callurl(ch, index, urlmap[index].url, wg)
}
}

huangapple
  • 本文由 发表于 2013年12月31日 05:56:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/20848236.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定