<p>Hi,</p>
<p>since there is an interface for getting string out of a type (stringer) I was wondering if there is something similar for integers. <a href="https://play.golang.org/p/_GNGvBCfapY" rel="nofollow">Example</a></p>
<hr/>**评论:**<br/><br/>TheMerovius: <pre><pre><code>type Inter interface {
Int() int
}
</code></pre>
<p>The way Go interfaces work mean, that if you observe a pattern, you can just declare that interface and use it.</p>
<p>FWIW, there are two subtly distinct concepts that the term "interface" is used in: a) provided interfaces, that is the set of methods a type gives you and b) required interfaces, that is the set of methods you need from a type to be able to use it.
Go interfaces are about b), not about a), so they should be consumer-defined.</p>
<p>I.e. <code>fmt.Stringer()</code> is an interface created by <code>fmt</code>, so that you can tell it how to format a type. If you have a package and give people the ability to specify how to create an integer out of a thing, you can have it define above interface.</p>
<p>It seems non-obvious to me, however, why you'd <em>want</em> that. Your example is weird to me; it would make much more sense to me to call that method <code>Mileage</code> (actually, you just shouldn't make it a method but an exported field, but that's beside the point).</p></pre>shovelpost: <pre><p>While searching for <code>Inter</code> I discovered:</p>
<pre><code>type GoStringer interface {
GoString() string
}
</code></pre>
<p>Which means that we can do: <a href="https://play.golang.org/p/3qH_l87W1qj" rel="nofollow">https://play.golang.org/p/3qH_l87W1qj</a></p>
<p>I had no idea this was a thing :)</p></pre>ls42: <pre><blockquote>
<p>is an interface created by <code>fmt</code></p>
</blockquote>
<p>Oh, that I didn't know. I assumed that <code>Stringer()</code> was somehow a global thing; Now it makes more sense. (And it explains why <code>println()</code> works differently in that regard then <code>fmt.Println()</code>). Thanks for pointing that out.</p>
<blockquote>
<p>why you'd want that</p>
</blockquote>
<p>I had the impression that implementing a <code>String()</code> method would somehow work on a global scope, and was used to get a <em>defined</em> string out of a type. Like "if you want to convert this type to a string, I'd call this <code>.String()</code> method of that type (if it has one) and that's it". I found the idea nifty and assumed it would be nice to have something similar with integers. Simply using <code>c.Mileage</code> makes sense, now. </p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传