package mainimport ( "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)
1 回答

動漫人物
TA貢獻1815條經驗 獲得超10個贊
我想你正在尋找: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 := &x
x = append(x, (*x)...) // x = []int{1, 2, 3, 1, 2, 3}
- 1 回答
- 0 關注
- 124 瀏覽
添加回答
舉報
0/150
提交
取消