gpt4 book ai didi

go - 我什么时候应该返回值而不是修改接收者指针?

转载 作者:IT王子 更新时间:2023-10-29 01:47:09 25 4
gpt4 key购买 nike

我有一个用于结构 ProofOfWork 的方法,它应该修改结构成员 NonceHash。所以我想知道它是否应该在 Run 方法中修改给定实例的这两个成员,或者应该将这两个变量作为返回值。

下面是带有返回变量的Run方法:

// Run performs a proof-of-work
func (pow *ProofOfWork) Run() (int, []byte) {
var hashInt big.Int
var hash [32]byte
nonce := 0

fmt.Printf("Mining the block containing \"%s\"\n", pow.block.Data)
for nonce < maxNonce {
data := pow.prepareData(nonce)

hash = sha256.Sum256(data)
fmt.Printf("\r%x", hash)
hashInt.SetBytes(hash[:])

if hashInt.Cmp(pow.target) == -1 {
break
} else {
nonce++
}
}
fmt.Print("\n\n")

return nonce, hash[:]
}

然后是没有任何返回变量的版本:

func (pow *ProofOfWork) Run() {
var hashInt big.Int
var hash [32]byte // the type of hash value is defined by result of the sha256 function
nonce := 0

for nonce < MaxNonce {
data := pow.prepareData(nonce)
hash := sha256.Sum256(data)
hashInt.SetBytes(hash[:])
if hashInt.Cmp(pow.target) == -1 {
// the nonce found
break
} else {
nonce++
}
}
pow.block.Hash = hash[:]
pow.block.Nonce = nonce
}

最佳答案

您显示的两个选项有时可能会有用。我可以提出另一种可能性吗?在 Go 中,我们应该比在其他语言中更频繁地使用函数。一个简单的函数可能正是您正在寻找的:

// Run performs a proof-of-work
func Run(pow *ProofOfWork) (int, []byte) {
var hashInt big.Int
var hash [32]byte
nonce := 0

fmt.Printf("Mining the block containing \"%s\"\n", pow.block.Data)
for nonce < maxNonce {
data := pow.prepareData(nonce)

hash = sha256.Sum256(data)
fmt.Printf("\r%x", hash)
hashInt.SetBytes(hash[:])

if hashInt.Cmp(pow.target) == -1 {
break
} else {
nonce++
}
}
fmt.Print("\n\n")

return nonce, hash[:]
}

我可能会让 ProofOfWork 成为一个接口(interface),并以这种方式抽象 Run。

关于go - 我什么时候应该返回值而不是修改接收者指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48489703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com