0

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

I am trying to mimic my problem. I have dynamic number of function calls i.e randoms and dynamic number of results. I need to append all of the results i.e numbers in this case.

I am able to do this with iteration and no issues with it. I am looking for a way to do something like nums = append(nums, res). Is there any way to do this/any built-in methods/did I misunderstand the pointers?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Gibbs
  • 21,904
  • 13
  • 74
  • 138

1 Answers1

3

I think you're looking for append(nums, (*res)...):

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

playground

See this answer for more about ..., but in short it expands the contents of a slice. Example:

x := []int{1, 2, 3}
y := []int{4, 5, 6}
x = append(x, y...) // Now x = []int{1, 2, 3, 4, 5, 6}

Further, since you have a pointer to a slice, you need to dereference the pointer with *.

x := []int{1, 2, 3}
y := &x
x = append(x, (*x)...) // x = []int{1, 2, 3, 1, 2, 3}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189