I don't understand this program at all. Can you guys explain? I'm not an experienced programmer. Just started learning

agolangf · · 394 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>import &#34;errors&#34; import &#34;fmt&#34; By convention, errors are the last return value and have type error, a built-in interface. func f1(arg int) (int, error) { if arg == 42 { errors.New constructs a basic error value with the given error message. return -1, errors.New(&#34;can&#39;t work with 42&#34;) } A nil value in the error position indicates that there was no error. return arg + 3, nil } It’s possible to use custom types as errors by implementing the Error() method on them. Here’s a variant on the example above that uses a custom type to explicitly represent an argument error. type argError struct { arg int prob string } func (e <em>argError) Error() string { return fmt.Sprintf(&#34;%d - %s&#34;, e.arg, e.prob) } func f2(arg int) (int, error) { if arg == 42 { In this case we use &amp;argError syntax to build a new struct, supplying values for the two fields arg and prob. return -1, &amp;argError{arg, &#34;can&#39;t work with it&#34;} } return arg + 3, nil } func main() { The two loops below test out each of our error-returning functions. Note that the use of an inline error check on the if line is a common idiom in Go code. for _, i := range []int{7, 42} { if r, e := f1(i); e != nil { fmt.Println(&#34;f1 failed:&#34;, e) } else { fmt.Println(&#34;f1 worked:&#34;, r) } } for _, i := range []int{7, 42} { if r, e := f2(i); e != nil { fmt.Println(&#34;f2 failed:&#34;, e) } else { fmt.Println(&#34;f2 worked:&#34;, r) } } If you want to programmatically use the data in a custom error, you’ll need to get the error as an instance of the custom error type via type assertion. _, e := f2(42) if ae, ok := e.(</em>argError); ok { fmt.Println(ae.arg) fmt.Println(ae.prob) } }</p> <hr/>**评论:**<br/><br/>SilverWingedSeraph: <pre><p>Please use Pastebin, GitHub Gist, or at least proper Reddit formatting, so we can actually read your code.</p></pre>saturn_vk: <pre><p>Rather, just use play.golang.org</p></pre>shovelpost: <pre><p>It seems you have copy pasted the code (and the text) from <a href="https://gobyexample.com/errors" rel="nofollow">this page</a>.</p> <p>The page text (on the left) explains very well what each part of the code (on the right) does. What exactly is it that you do not understand?</p></pre>

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

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