如何在golang中的哈希算法之间动态切换?

I want to be able to switch between hash algorithms depending on caller input, for example, implement a function:

func GenericHash(dat []byte, hash unint) (string, error) { ... }

where hash is the algorithm type as specified by crypto.Hash.

I'm not sure how to write this function, in particular, where the import statements should go. If I include all the import statements for algorithms that I will use at the top, go complains that they're imported and not used. Is there anyway to import on demand?

What you need to do is import the packages for their side effects only (i.e. use the blank identifier when importing the packages). This means that the imported packages' init functions will be executed, but you will not be able to access any of their exported members directly.

Here is one way you could solve your problem:

import (
  "errors"
  "encoding/hex"
  "crypto"
  _ "crypto/md5"
  _ "crypto/sha1"
  // import more hash packages
)

func GenericHash(dat []byte, hash crypto.Hash) (string, error) {
  if !hash.Available() {
    return "", errors.New("hash unavailable")
  }
  h := hash.New()
  return hex.EncodeToString(h.Sum(dat)), nil
}