如何知道我们可以在 Go 包中使用哪些函数?

huangapple go评论89阅读模式
英文:

How to know the functions we can use with a go package?

问题

我正在学习Go语言并编写我的第一个Go程序,借助一些网络资源的帮助:

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)
	
}

它可以编译并按预期工作,但我无法自己编写这段代码,因为如果我查看Go包参考sha256,我看不到Write()Sum()方法。在哪里可以找到这种信息?也许我没有阅读正确的文档,或者有一种我没有注意到的"继承"方式。

英文:

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.

答案1

得分: 5

哈希实现都是通过一个共同的hash.Hash 接口提供的。

如果你查看sha512.New的文档,你会看到它返回一个hash.Hash,其中列出了所有Hash特定的方法。

hash.Hash接口中的第一个字段是一个嵌入io.Writer,它提供了标准的Write方法。

所有这些值在文档中都是链接,你可以跟随这些链接找到所需的定义,甚至源代码。

英文:

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.

答案2

得分: 0

Sum()Write() 函数是 Hash 接口的一部分,该接口由各种不同类型的哈希实现。

英文:

The Sum() and Write() functions are part of the Hash interface, which is implemented by all different kind of hashs.

答案3

得分: 0

hash.Hash 返回一个 Hash 接口,其中包含 io.Writer。如果你查看 io.Writer,你会发现一个 Writer 接口,它有一个 Write() 方法。因为 sha512 包实现了 Write 方法,所以你可以将 Write 方法作为 hasher 方法调用。

访问接口的唯一要求是在你的自定义范围内实现定义的方法。

英文:

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.

huangapple
  • 本文由 发表于 2016年2月9日 23:04:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/35295339.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定