我有类似的东西
unixtime := time.Now().Unix()
unixtimeStr := string(unixtime)
soup := make([]byte, len(data) + len(nonce) + len(unixtimeStr) + len(previousHash))
copy(soup[:], data)
copy(soup[len(data):], nonce)
copy(soup[len(data) + len(nonce):], []byte(unixtimeStr))
copy(soup[len(data) + len(nonce) + len(unixtimeStr):], previousHash)
hasher := sha1.New()
hasher.Write(soup)
var hash []byte = hasher.Sum(nil)
data
,nonce
和previousHash
的类型为[]byte
。我觉得它很脏而且不可读!
我想要一种更面向对象的编码风格,例如
soup := data.concat(nonce).concat([]byte(unixtimeStr)).concat(previousHash)
或至少像
soup := concat(data, nonce, ...)
您将如何编写此代码段?
最佳答案
例如,
var data, nonce, previousHash []byte
unixtime := strconv.FormatInt(time.Now().Unix(), 10)
hasher := sha1.New()
hasher.Write(data)
hasher.Write(nonce)
hasher.Write([]byte(unixtime))
hasher.Write(previousHash)
hash := hasher.Sum(nil)
或者,
var data, nonce, previousHash []byte
unixtime := strconv.FormatInt(time.Now().Unix(), 10)
soup := make([]byte, 0, len(data)+len(nonce)+len(unixtime)+len(previousHash))
soup = append(soup, data...)
soup = append(soup, nonce...)
soup = append(soup, unixtime...)
soup = append(soup, previousHash...)
hasher := sha1.New()
hasher.Write(soup)
hash := hasher.Sum(nil)
笔记:
unixtime := time.Now().Unix()
unixtimeStr := string(unixtime)
是荒谬的。始终是Unicode替换字符。例如,
package main
import (
"fmt"
"time"
"unicode"
)
func main() {
unixtime := time.Now().Unix()
unixtimeStr := string(unixtime)
fmt.Println(unixtimeStr == string(unicode.ReplacementChar))
}
输出:
true
要将整数转换为字符串,请使用
strconv
包。例如,package main
import (
"fmt"
"strconv"
"time"
)
func main() {
unixtimeStr := strconv.FormatInt(time.Now().Unix(), 10)
fmt.Println(unixtimeStr)
}
输出:
1257894000
关于go - 连接[] byte和哈希,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54610384/