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

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      }

图片转代码服务由CSDN问答提供 功能建议

我读了exec.Start的代码,其中有些地方使我感到困惑。 [] F中的(* Cmd).stdin / out / err,(* Cmd).stdXX是什么意思?

  291 type F func(* Cmd)(  * os.File,错误)
 292,用于_,setupFd:=范围[] F {(* Cmd).stdin,(* Cmd).stdout,(* Cmd).stderr} {
 293 fd,错误:  = 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条)

相关推荐 更多相似问题