首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >什么时候应该返回值而不是修改接收者指针?

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

Stack Overflow用户
提问于 2018-01-28 18:09:57
回答 1查看 96关注 0票数 2

我有一个用于struct ProofOfWork的方法,它应该修改struct成员、、NonceHash。因此,我想知道它是应该在方法运行中修改给定实例的这两个成员,还是应该将这两个变量作为返回。

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

代码语言:javascript
复制
// 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[:]
}

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

代码语言:javascript
复制
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
}
EN

回答 1

Stack Overflow用户

发布于 2018-01-28 20:53:37

您展示的这两个选项有时可能都很有用。请允许我提出另一种可能性。在Go中,我们应该比在其他语言中更频繁地使用函数。一个简单的函数可能正是您所要寻找的:

代码语言:javascript
复制
// 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成为一个接口,并以这种方式抽象地运行。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48489703

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档