我遵循有关在go中构建区块链的文章:https ://jeiwan.cc/posts/building-blockchain-in-go-part-2/
当我学习第2部分时,我无法在prepareDate函数中运行代码。它总是抛出一个错误:
未定义:IntToHex。
这是我的代码:
func (pow *ProofOfWork) prepareData(nonce int) []byte {
data := bytes.Join(
[][]byte{
pow.block.PrevBlockHash,
pow.block.Data,
IntToHex(pow.block.Timestamp),
IntToHex(int64(targetBits)),
IntToHex(int64(nonce)),
},
[]byte{},
)
return data
}
Run Code Online (Sandbox Code Playgroud)
看起来该文章的作者将其功能保留在他/她的示例中,或暗示读者自己编写了该函数。将整数表示为以16为底的格式非常容易,并且可以使用标准库的strconv包来完成。以下是一个我认为适合您的程序的示例:
func IntToHex(n int64) []byte {
return []byte(strconv.FormatInt(n, 16))
}
Run Code Online (Sandbox Code Playgroud)