How to return an error or data for a function ?

polaris · · 306 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>thing, err := MakeThing()</p> <p>how to make func MakeThing to return data or error ?</p> <p>thanks and regards</p> <hr/>**评论:**<br/><br/>mixedCase_: <pre><p>Hi! It seems you&#39;re new to Go. I heavily advise you to fully read and comprehend these three links from the documentation at least once in order to save yourself a lot of guessing how things work in Go:</p> <p><a href="https://tour.golang.org/welcome/2" rel="nofollow">https://tour.golang.org/welcome/2</a><br/> <a href="https://golang.org/doc/code.html" rel="nofollow">https://golang.org/doc/code.html</a><br/> <a href="https://golang.org/doc/effective_go.html" rel="nofollow">https://golang.org/doc/effective_go.html</a></p> <p>I promise you will not be wasting your time reading them!</p></pre>bussiere: <pre><p>thanks a lot i will :)</p></pre>DualRearWheels: <pre><p>This should be voted to top. Question is most basic one, good reading of manual should solve it along with a lot of other things new Go users could get stuck with.</p> <p>There is no replacement for learning from docs in correct order. Knowledge is layered, if you lack good foundations then process will be slow and frustrating and final products will be bad.</p></pre>JokerSp3: <pre><p>the idiomatic way would be to do something like</p> <pre><code>func MakeThing() (thing, error) { t := thing{} if condition { return t, errors.New(&#34;this is an error&#34;) } return t, nil } </code></pre></pre>bussiere: <pre><p>thanks :)</p></pre>caseynashvegas: <pre><p>Beat me in by a second!</p></pre>nesigma: <pre><p>I usually find myself doing this:</p> <pre><code>func MakeThing() (*thing, error) { t := &amp;thing{} if condition { return nil, errors.New(&#34;this is an error&#34;) } return t, nil } </code></pre> <p>When is it appropriate to use each case?</p></pre>caseynashvegas: <pre><p>If I am understanding your question, the following should playground example might answer it.<br/> <a href="https://play.golang.org/p/GETLz1LgU8" rel="nofollow">https://play.golang.org/p/GETLz1LgU8</a></p></pre>bussiere: <pre><p>thanks for your time</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

306 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传