英文:
How to append big.Int numbers to a [ ]big.Int slice?
问题
我想将big.Int
类型的数字追加到一个big.Int
切片中。我尝试了以下代码:
a := big.NewInt(10)
b := big.NewInt(20)
arr := new([]big.Int)
arr = append(arr, a, b)
然而,它返回了错误信息:first argument to append must be slice; have *[]big.Int
。
那么,我该如何向big.Int
切片中追加元素呢?
英文:
I want to append big.Int
numbers to a slice of big.Int
type. I tried the following:
a := big.NewInt(10)
b := big.NewInt(20)
arr := new([]big.Int)
arr = append(arr, a, b)
However it returned with the error first argument to append must be slice; have *[]big.Int
.
So how do I append to a big.Int
slice?
答案1
得分: 2
你在这里有两个选项。big.NewInt()
返回一个指向 big.Int
值的引用。所以,如果你只需要在数组中保留值,你可以使用以下方法:
a := big.NewInt(10)
b := big.NewInt(20)
var arr []big.Int
arr = append(arr, *a, *b)
如果你需要在数组中存储值的引用,你可以使用以下方法:
var arr []*big.Int
arr = append(arr, a, b)
英文:
you have two options here. big.NewInt()
returns reference to a big.Int
value. So If you need to keep values only in the array you can use following.
a := big.NewInt(10)
b := big.NewInt(20)
var arr []big.Int
arr = append(arr, *a, *b)
If you need to store reference of the values in the array, You can use following.
var arr []*big.Int
arr = append(arr, a, b)
答案2
得分: 1
你错误地使用了分配内存给切片的方法。使用new
获取指针并将其与make
一起调用只会使事情变得复杂。你可以初始化一个空切片,然后使用append
方法。
而且,NewInt
返回一个包含值的指针,在存储到切片之前需要解引用它。
var arr []big.Int
arr = append(arr, *a, *b)
或者使用make
分配一个数组并返回一个引用该数组的切片,然后通过索引存储值。
arr := make([]big.Int, 2)
英文:
You are incorrectly using the method to allocate memory to slice. Using new
to get a pointer and calling it with make
just complicates things. You could just initialise an empty slice and use append
And moreover NewInt
returns a pointer containing the value, dereference it before storing in the slice.
var arr []big.Int
arr = append(arr, *a, *b)
or use make
to allocate an array and return a slice that refers to that array and store the values by indices
arr := make([]big.Int, 2)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论