How to generate hash number of a string in Go?

前端 未结 2 1243
遇见更好的自我
遇见更好的自我 2021-02-02 07:05

For example:

hash(\"HelloWorld\") = 1234567

Is there any built-in function could do this ?

Thanks.

2条回答
  •  面向向阳花
    2021-02-02 07:33

    The hash package is helpful for this. Note it's an abstraction over specific hash implementations. Some ready made are found in the package subdirectories.

    Example:

    package main
    
    import (
            "fmt"
            "hash/fnv"
    )
    
    func hash(s string) uint32 {
            h := fnv.New32a()
            h.Write([]byte(s))
            return h.Sum32()
    }
    
    func main() {
            fmt.Println(hash("HelloWorld"))
            fmt.Println(hash("HelloWorld."))
    }
    

    (Also here)


    Output:

    926844193
    107706013
    

提交回复
热议问题