dongnai6973 2015-05-16 16:13
浏览 67
已采纳

习惯用法Go,用于抽象资源分配/取消分配

Is there an idiomatic Go way for abstracting resource allocation/deallocation? My initial guess is to abstract the allocation/deallocation in a higher-order function:

func withResource(f func(Resource)error) error {
    // allocate resource
    // defer free resource
    return f(resource)
}

However, this line of thinking is borrowed directly from the functional paradigm and doesn't seem to align well with Go's largely imperative nature.

As a concrete example, running a daemon for the duration of a block of code is a recurring theme in my current project, so I've created a withDaemon function to abstract the commonality:

func withDaemon(
    cmd *exec.Cmd,
    f func(io.ReadCloser, io.ReadCloser, io.WriteCloser) error,
) error {
    stdout, err := cmd.StdoutPipe()
    if err != nil {
        return fmt.Errorf("couldn't get stdout: %v", err)
    }

    stderr, err := cmd.StdoutPipe()
    if err != nil {
        return fmt.Errorf("couldn't get stderr: %v", err)
    }

    stdin, err := cmd.StdinPipe()
    if err != nil {
        return fmt.Errorf("couldn't get stdin: %v", err)
    }

    if err := cmd.Start(); err != nil {
        return fmt.Errorf("failed to start: %v", err)
    }

    defer func() {
        cmd.Process.Kill()
        cmd.Wait()
    }

    return f(stdout, stderr, stdin)
}
  • 写回答

1条回答 默认 最新

  • dongnaigu2052 2015-05-16 16:37
    关注

    I think that the idiomatic way would be to create a Daemon type, and to just use defer in the caller:

    d := NewDaemon(...)
    defer d.Stop()
    doWhatever()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大