在服务 a 中,我有一个像这样进行哈希处理的字符串:
fun string.tohash(): long {
var hashcode = this.hashcode().tolong()
if (hashcode < 0l) {
hashcode *= -1
}
return hashcode
}
我想在用 golang 编写的服务 b 中复制这段代码,因此对于同一个单词,我得到完全相同的哈希值。据我从 kotlin 文档中了解到,应用的哈希返回一个 64 位整数。所以在 go 中我这样做:
func hash(s string) int64 {
h := fnv.new64()
h.write([]byte(s))
v := h.sum64()
return int64(v)
}
但是在进行单元测试时我没有得到相同的值。我得到:
func test_hash(t *testing.t) {
tests := []struct {
input string
output int64
}{
{input: "papafritas", output: 1079370635},
}
for _, test := range tests {
got := hash(test.input)
assert.equal(t, test.output, got)
}
}
结果:
7841672725449611742
我做错了什么吗?
正确答案
Java 以及 Kotlin 使用与 Go 不同的哈希函数。
可能的选项是:
- 使用标准哈希函数。
- 在 Go 中重新实现字符串的 Java hashCode。