英文:
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
如果你查看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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论