dongxie548548 2016-12-03 22:34
浏览 22
已采纳

去吧,是否可以将延迟放在子函数中

Is it possible to put defer in sub function?

I.e., for line 12~16 of func test1() in https://play.golang.org/p/evabhcjvNs (enclosed below)

Is there any possibility to put them in sub function? Like what I tried in test2() (but that behavior is different than test1()).

The reason I'm asking is that, for line 12~16 of func test1(), my actual code is to restore the variable from persistent data, then use defer to save it when test1() is done. However, there are cases that the whole restore/save is not necessary, so I'm thinking a better way to control it.

thanks

package main

import "log"

func main() {
    test1()
    log.Printf("==== 
")
    test2()
}

func test1() {
    r, err := Open("a")
    if err != nil {
        log.Fatalf("error opening 'a'
")
    }
    defer r.Close()

    r.Use()
}

func test2() {
    r := subc()
    r.Use()
}

func subc() *Resource {
    r, err := Open("a")
    if err != nil {
        log.Fatalf("error opening 'a'
")
    }
    defer r.Close()
    return r
}

type Resource struct {
    name string
}

func Open(name string) (*Resource, error) {
    log.Printf("opening %s
", name)
    return &Resource{name}, nil
}

func (r *Resource) Use() error {
    log.Printf("using %s
", r.name)
    return nil
}

func (r *Resource) Close() error {
    log.Printf("closing %s
", r.name)
    return nil
}
  • 写回答

1条回答 默认 最新

  • dq8081 2016-12-03 23:53
    关注

    I think I understand what you're asking. You want to know if a function can place a function on the defer stack of the caller. The answer to that is no. One possible solution to this is to have the function that wants to defer something return that function to the caller and have the caller do the defer. For example:

    func test2() {
        r, cleanup := subc()
        defer cleanup()
        r.Use()
    }
    
    func subc() (*Resource, func()) {
        r, err := Open("a")
        if err != nil {
            log.Fatalf("error opening 'a'
    ")
        }
        return r, func() { r.Close() }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败