TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Common Interface Mistakes in Go

25 点作者 nnx11 个月前

4 条评论

randomdata11 个月前
<i>&gt; You create interfaces purely for testing</i><p>The interface cost is real, but I&#x27;m not yet convinced the other solutions for simulating errors while under test are not even more costly. testcontainers is a complete non-starter. I&#x27;m not, for example, going to physically crash my hard drive to get the appropriate errors out of it.<p>If you are not documenting your failure cases in your tests, you may as well not write any code at all. The failure states are the most important part of your application.
kazinator11 个月前
Should be titled, &quot;Advice for people coming to Go from working on nothing but 1990s COM objects&quot;.<p>Don&#x27;t return an interface? Why would I do that, when I can store it through void ** parameter you pass to me? Ha!<p><pre><code> HRESULT QueryInYourFace( REFIID riid, void **ppvObject ); </code></pre> And I won&#x27;t make a move without designing interfaces. Interfaces is all there is, all the way down!<p>Before we write a line of code, we fill a whiteboard with boxes that have antennas with little balls on the end. Those are interfaces.
silisili11 个月前
Overall this is pretty solid advice, with only two things I disagreed with a bit:<p>&gt; Go is still a new language<p>Go is between 12 and 17 years old, depending on how you look at it. It&#x27;s not as old as the big players, but it&#x27;s far from new.<p>&gt; Do not think returning an interface is a bad idea<p>It&#x27;s almost always a bad idea to return an interface. Return a type that implements said interface(s). If you want to hide away details, use lowercase to not export them. This section had a solid point, then backtracked a little, and I wish it hadn&#x27;t.
评论 #40807892 未加载
评论 #40808287 未加载
BrannonKing11 个月前
The article doesn&#x27;t go into pointers to interfaces, which is a place of many footguns. It also leaves out generics. Suppose I have this structure:<p><pre><code> type State[TValue cmp.Ordered, TCost any] interface { TransitionTo(context Context[TValue, TCost], value TValue) State[TValue, TCost] ... other methods </code></pre> where Context is also a generic interface. I should add a TContext generic type to State instead of casting it inside my State implementation. It definitely leads to a proliferation of generic types being required on all methods that touch these things. I used to use Go for its terseness. Generics make it much less terse, but I like what they enable.