在golang中,如何从一个函数返回一个类型为int的切片给另一个函数?

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

In golang, how to return a slice of type int from a function to another function?

问题

I have used channels to communicate..

   b := make([]int,0)  //这是我创建的切片。

我正在向切片中添加值,并且我想将存储在b中的最终切片传递给另一个函数返回。我使用了以下代码:

   slic := make(chan int)
   go func() { slic <- input()} ()
   slice := <-slic
   fmt.Println(slice)

我得到了这个错误:"无法将b(类型为[]int)用作返回参数中的int类型。

英文:

I have used channels to communicate..

   b := make([]int,0)  //This is the slice I have created.

I was appending values to the slice and I want to transfer the final slice stored in b to be returned to another function.. I have used this code..

   slic := make(chan int)
   go func() { slic &lt;- input()} ()
   slice := &lt;-slic
   fmt.Println(slice)

I am getting this error:"can't use b (type []int) as type int in return argument."

答案1

得分: 3

将你的chan类型更改为以下内容:

make(chan []int)

或者选择你的[]int中的一个索引来发送到你的chan int

无论哪种方式,int[]int都是不同的类型,就像chan intchan []int一样。

英文:

Change your chan make to this:

make(chan []int)

Or select an index of your []int to send on your chan int.

Either way int and []int are distinct types, as chan int and chan []int are.

huangapple
  • 本文由 发表于 2013年7月13日 01:04:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/17620270.html
匿名

发表评论

匿名网友

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

确定