double2022 2014-07-16 16:16
浏览 19
已采纳

具有多个字段的嵌入式结构的文字初始化

type fun struct {}

type starcraft struct {
    *fun // embedding struct
    mu sync.Mutex
}

I know I can literal initial struct startcraft as:

f := &fun{}
s := starcraft{f, *new(sync.Mutex)}

I don't like it, since:

a. I don't want to initialize sync.Mutex by myself

b. in this case there is a wasted copy using *new(sync.Mutex).

Is there any better way?

  • 写回答

2条回答 默认 最新

  • dsvbtgo639708 2014-07-16 17:33
    关注

    You can name embedded structs:

    s := starcraft{
        fun: f,
        mu:  *new(sync.Mutex),
    }
    

    You don't need to use new to create a zero value. If the type is already declared, you don't need to initialize it at all, or you can use the zero value.

    s := starcraft{
        fun: f,
        mu:  sync.Mutex{},
    }
    

    And since the zero value for a Mutex is a valid, unlocked Mutex (http://golang.org/pkg/sync/#Mutex), you definitely don't need to initialize it, and can leave it out of the struct literal.

    s := starcraft{
        fun: f,
    }
    

    On top of that, it's also very common to embed the Mutex and call Lock and Unlock directly on the outer struct.

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

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算