什么时候应该返回值而不是修改接收器指针?

问题描述 投票:2回答:1

我有一个struct ProofOfWork的方法,它应该修改结构成员Nonce和Hash。所以我想知道它是否应该在方法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
1个回答
0
投票

您展示的两个选项有时可能很有用。我可以提出另一种可能性。在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成为一个接口,并以这种方式抽象运行。

© www.soinside.com 2019 - 2024. All rights reserved.