douxi3432 2015-01-27 12:11
浏览 59
已采纳

golang中有惯用范围语义吗?

I wonder if there is any idiomatic way to represent scoped semantics. By scoped I mean things like:

  • scoped mutex (oneliner instead of explicit Lock + deffered Unlock),
  • logging function (or any code block) entrance and exit,
  • measuring execution time.

Example code for first two bullets:

package main

import "log"
import "sync"

func Scoped(m *sync.Mutex) func() {
    m.Lock()
    return func() {
        m.Unlock()
    }
}

func Log(what string) func() {
    log.Println(what, "started")
    return func() {
        log.Println(what, "done")
    }
}

func main() {
    defer Log("testing")()

    m := &sync.Mutex{} // obviously mutex should be from other source in real life
    defer Scoped(m)()
    // use m
}

https://play.golang.org/p/33j-GrBWSq

Basically we need to make one function call just now (eg mutex lock), and one call should be postponed to defer (eg mutex unlock). I propose just returning unnamed function here, but it can be easily named (return struct with function field).

There is only one problem: user can forget to 'call' result of first call.

This code is (can be) idiomatic?

  • 写回答

4条回答 默认 最新

  • dqhgjay5753 2015-01-27 12:52
    关注

    I do not believe there is an idiomatic way to do this. I'm not sure why you'd want to either, is it really so bad to write

    m.Lock()
    defer m.Unlock()
    

    ?

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

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大