【问题标题】:Merge pointer to a slice合并指向切片的指针
【发布时间】:2021-05-03 07:24:26
【问题描述】:

playground

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

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

我可以用iteration 做到这一点,而且没有问题。我正在寻找一种方法来做类似nums = append(nums, res) 的事情。有没有办法做到这一点/任何内置方法/我误解了指针吗?

【问题讨论】:

    标签: go


    【解决方案1】:

    我想你正在寻找append(nums, (*res)...)

           nums = append(nums, (*res)...)
    

    playground

    有关... 的更多信息,请参见this answer,但简而言之,它扩展了切片的内容。示例:

    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 := &x
    x = append(x, (*x)...) // x = []int{1, 2, 3, 1, 2, 3}
    

    【讨论】:

      猜你喜欢
      • 2015-05-01
      • 1970-01-01
      • 2015-02-21
      • 1970-01-01
      • 2021-09-15
      • 2015-07-04
      • 2017-08-11
      相关资源
      最近更新 更多