我有一个用于struct ProofOfWork的方法,它应该修改struct成员、、Nonce和Hash。因此,我想知道它是应该在方法运行中修改给定实例的这两个成员,还是应该将这两个变量作为返回。
下面是带有返回变量的运行方法:
// 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
}发布于 2018-01-28 20:53:37
您展示的这两个选项有时可能都很有用。请允许我提出另一种可能性。在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成为一个接口,并以这种方式抽象地运行。
https://stackoverflow.com/questions/48489703
复制相似问题