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()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器