猿问

指向切片的合并指针

package main


import (

    "fmt"

    "math/rand"

)


func randoms() *[]int {

  var nums []int = make([]int, 5, 5) //Created slice with fixed Len, cap

  fmt.Println(len(nums))

  for i := range [5]int{} {//Added random numbers.

     nums[i] = rand.Intn(10)

  }

  return &nums//Returning pointer to the slice

}


func main() {

    fmt.Println("Hello, playground")

    var nums []int = make([]int, 0, 25)

    for _ = range [5]int{} {//Calling the functions 5 times

       res := randoms() 

       fmt.Println(res)

       //nums = append(nums, res)

       for _, i := range *res {//Iterating and appending them

         nums = append(nums, i)

       }

    }

    fmt.Println(nums)

}

我试图模仿我的问题。我有动态数量的函数调用,即动态的结果数量。我需要附加所有结果,即.randomsnumbers in this case


我能够做到这一点,没有问题。我正在寻找一种方法来做这样的事情。有没有办法做到这一点/任何内置方法/我是否误解了指针?iterationnums = append(nums, res)


白衣染霜花
浏览 129回答 1
1回答

动漫人物

我想你正在寻找:append(nums, (*res)...)       nums = append(nums, (*res)...)操场有关 的更多信息,请参阅此答案,但简而言之,它扩展了切片的内容。例:...x := []int{1, 2, 3}y := []int{4, 5, 6}x = append(x, y...) // Now x = []int{1, 2, 3, 4, 5, 6}此外,由于您有一个指向切片的指针,因此需要使用 取消引用该指针。*x := []int{1, 2, 3}y := &xx = append(x, (*x)...) // x = []int{1, 2, 3, 1, 2, 3}
随时随地看视频慕课网APP

相关分类

Go
我要回答