douweng1935 2018-01-28 18:09
浏览 25

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

I have a method for the struct ProofOfWork which should modify the struct members Nonce and Hash. So I wonder whether it should modify these two members of the given instance inside the method Run or should make these two variables as a return.

So here is the method Run with return variables:

// 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\"
", pow.block.Data)
    for nonce < maxNonce {
        data := pow.prepareData(nonce)

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

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

")

    return nonce, hash[:]
}

Then the version without any return variables:

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
}
  • 写回答

1条回答 默认 最新

  • dtmjl4427 2018-01-28 20:53
    关注

    Both options you show might be useful sometimes. May I propose another possibility. In Go we should use functions much more often then in other languages. A plain function might be exactly what you are looking for:

    // 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\"
    ", pow.block.Data)
        for nonce < maxNonce {
            data := pow.prepareData(nonce)
    
            hash = sha256.Sum256(data)
            fmt.Printf("%x", hash)
            hashInt.SetBytes(hash[:])
    
            if hashInt.Cmp(pow.target) == -1 {
                break
            } else {
                nonce++
            }
        }
        fmt.Print("
    
    ")
    
        return nonce, hash[:]
    }
    

    I would probably make ProofOfWork an interface, and abstract Run that way.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用