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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化