An example using io.Pipe() and a small bit of channels/goroutines

xuanbao · · 185 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>People are pretty much always looking for examples of how to use channels and goroutines and the following code has a small example of that. <a href="" rel="nofollow"></a></p> <p>Instead of returning an error the <code>Commands()</code> function instead returns a writer, reader, and an error channel because some of the work can&#39;t be completed until the writer returned is closed. This allows the end user to get everything with a single function call but still check for errors in the work in case any happen to occur.</p> <p>The underlying <code>Cmds</code> type is also (at least to me) a neat example of how you can use the <a href="" rel="nofollow">io.Pipe()</a> function to pipe output from one place as input to another. One of the cooler functions in the <code>io</code> package that doesn&#39;t get enough attention.</p> <hr/>**评论:**<br/><br/>epiris: <pre><p>Well done, I&#39;m curious though why the cmds struct has a slice of WriteCloser. Wouldn&#39;t there just be one, the head of the pipe? Or are you suppose to provide each commands Stdlin separately? </p> <p>Edit: Oh I see after reading it, its just an oversight during setup. Maybe that Cmds struct should be private since it would be difficult to use, OR move all the external setup in New and Commands directly into the cmds struct. It&#39;s not clear what purpose New serves, other than giving you a slightly more setup CMDS struct, but slightly less than Commands returns?</p></pre>joncalhoun: <pre><p>The <code>Cmds</code> struct should probably be private like you said. That was an oversight on my part.</p> <p>Honestly, when I originally wrote this I just created the <code>Cmds</code> version that is documented in the README, but then I got curious about a version more inline with how <code>io.Pipe()</code> works and wrote the other version today. It is much shorter (code-wise) when you ignore the error channel altogether, but when you actually check for errors they end up being similar. Just another way to solve the same problem I suppose.</p> <p>I will push an update w/ the <code>cmds</code> type being made private. Stating that so everyone doesn&#39;t think you are going crazy when I do it :)</p></pre>epiris: <pre><p>That makes sense, when those details are hidden the package will be clear and concise, thanks for taking the time to explain.</p></pre>

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

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