如何输入一个字符串,得到一个唯一的hashcode?
例子如下:
package main
import (
"fmt"
"hash/crc32"
)
// String hashes a string to a unique hashcode.
//
// crc32 returns a uint32, but for our use we need
// and non negative integer. Here we cast to an integer
// and invert it if the result is negative.
func String(s string) int {
v := int(crc32.ChecksumIEEE([]byte(s)))
if v >= 0 {
return v
}
if -v >= 0 {
return -v
}
// v == MinInt
return 0
}
func main(){
str := "123456abcd"
for i:=0; i<3;i++ {
hc := String(str)
fmt.Println("hashcode:", hc)
}
}
output:
hashcode: 2231530958
hashcode: 2231530958
hashcode: 2231530958
参考
https://godoc.org/github.com/hashicorp/terraform/helper/hashcode
https://github.com/hashicorp/terraform/blob/master/helper/hashcode/hashcode.go