如何将big.Int数字追加到[ ]big.Int切片中?

huangapple go评论95阅读模式
英文:

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)

参见Effective Go - 使用make进行分配

英文:

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)

See Effective Go - Allocation with make

huangapple
  • 本文由 发表于 2021年5月21日 16:13:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/67633116.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定