<p>Hello everyone, I'm new to Go and having some difficulties. I am working on a package manager project and have defined the type package as follows:</p>
<pre><code>type Package struct {
name string
author string
id string
}
</code></pre>
<p>However, the id of the package is the base64 encoded sha256 hash of the conjoined name and author string. How can I make the id variable act as such? </p>
<p>Example: a package with the name of "test" and author of "f9" returns the id "6A3WisT38mBMm/WHjZPP4dJEXixMag8Vu74jplHTt98="</p>
<p>Thank you for the help!</p>
<p>edit: I know how to use the built in crypto libraries, im just asking how to set the variable, so feel free to answer using pseudocode where the hash logic would occur</p>
<hr/>**评论:**<br/><br/>togamans: <pre><p>Also, consider:</p>
<p>func NewPackage(name, author string) *Package {
...
}</p>
<p>This is the common pattern for objects that require initialization. You compute your hash internally, and emit beautifully initialized Package pointers. </p></pre>FrequencyNine: <pre><p>please elaborate more on what would happen inside that function? im confused as to how this would work</p></pre>tcrypt: <pre><p>He means using a <a href="https://en.wikipedia.org/wiki/Constructor_(object-oriented_programming" rel="nofollow">constructor</a>, which I agree is probably the nicest way to do it.</p>
<p>Here's a modified version of <a href="/u/djherbis" rel="nofollow">/u/djherbis</a>' example that uses one. The NewPackage function accepts the package name and author, creates a *Package for them, and computes/sets the id.</p></pre>riscie: <pre><p>Where is the code?
/edit: sorry, did not mean to be rude but you said you've altered djherbis example? I can not see a second link, only the wikipedia article? Would be interested in this. </p></pre>tcrypt: <pre><p>Whoops, I completely forgot to paste the link :(</p>
<p><a href="https://play.golang.org/p/KpIHUyV2Np" rel="nofollow">https://play.golang.org/p/KpIHUyV2Np</a></p></pre>riscie: <pre><p>Thanks! </p></pre>togamans: <pre><p>Thanks for being less lazy than me :)</p></pre>djherbis: <pre><p><a href="https://play.golang.org/p/OFuvYPWSfz" rel="nofollow">https://play.golang.org/p/OFuvYPWSfz</a></p></pre>FrequencyNine: <pre><p>thank you, respect - frequencynine</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传