dongzong8110 2014-07-09 15:21
浏览 933
已采纳

exec.start中的这部分代码是什么意思?

I read the code of exec.Start,and there some part confusing me. (*Cmd).stdin/out/err in the []F,what's the meaning of (*Cmd).stdXX?

   291      type F func(*Cmd) (*os.File, error)
   292      for _, setupFd := range []F{(*Cmd).stdin, (*Cmd).stdout, (*Cmd).stderr} {
   293          fd, err := setupFd(c)
   294          if err != nil {
   295              c.closeDescriptors(c.closeAfterStart)
   296              c.closeDescriptors(c.closeAfterWait)
   297              return err
   298          }
   299          c.childFiles = append(c.childFiles, fd)
   300      }
  • 写回答

2条回答 默认 最新

  • dongzhan2461 2014-07-09 18:10
    关注

    Very Nice find, I did not know that idiom before. I will try to break it down. First We have exec.Cmd

    type exec.Cmd struct { ... }
    

    *Cmd has 3 many methods including stdin stdout stderr

    func (c *Cmd) stdin() (f *os.File, err error) {...}
    func (c *Cmd) stdout() (f *os.File, err error) {...}
    func (c *Cmd) stderr() (f *os.File, err error) {...}
    

    Now I want to call all these functions and do the same set of operations on each of them but I don't want to create another method because there are too many shared variable to pass by arguments.

    The first solution would be to just copy / paste the code 3 times. not nice.

    The second is to loop over an array of Functors. The Functor type would be func(c*Cmd)(f *os.File, err error) so we declare it as

    type F (c *Cmd) (f *os.File, err error)
    

    now we can create the array of functors. But how to select a *Cmd method ? simply using

    (*Cmd).<name of method>

    So it would be (*Cmd).stdin, (*Cmd.stdout), (*Cmd).stderr and we can use them as An array

    []F{ (*Cmd).stdin, (*Cmd.stdout), (*Cmd).stderr }
    

    we just need to call them now

    for _, setupFd := range []F{(*Cmd).stdin, (*Cmd).stdout, (*Cmd).stderr} {
        fd, err := setupFd(c)
        ...
    }
    

    Hope this helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致