I am learning the go language and write my first go program, with the help of some web sources:
package main
import (
"fmt"
"crypto/sha512"
"encoding/base64"
)
func main() {
ba := []byte("HelloWorld")
hasher := sha512.New()
hasher.Write(ba)
sha := base64.StdEncoding.EncodeToString(hasher.Sum(nil))
fmt.Printf(sha)
}
It compiles and works as expected, but I couldn't write this code myself since if i look at the Go package reference for sha256, I don't see the Write()
and the Sum()
methods. Where to find this kind of information? Maybe, I'm not reading the good document, or there is a sort of "inheritance" I didn't see.
The hash implementations are all provided through a common hash.Hash
interface.
If you look at the docs for sha512.New
, you'll see that it returns a hash.Hash
, which lists all the Hash
specific methods.
The first field in the hash.Hash
interface is an embedded io.Writer
, which is what provides the standard Write
method.
All these values are links in the documentation, which you can follow the to the required definitions, and even to the source.
The Sum()
and Write()
functions are part of the Hash
interface, which is implemented by all different kind of hashs.
hash.Hash
returns a Hash
interface, which include io.Writer
. If you check the io.Writer
, you will find a Writer
interface, which has a Write()
method. Because the sha512
package does implement the Write method, you can call the Write
as a hasher
method.
The only requirement to access an interface is to implemente the method defined in your custom scope.