V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
chor02
V2EX  ›  Go 编程语言

请教 go 一个继承中有 mutex 问题。

  •  
  •   chor02 · 2020-05-15 23:26:55 +08:00 · 4292 次点击
    这是一个创建于 1435 天前的主题,其中的信息可能已经有所发展或是发生改变。
    package main

    import (
    "fmt"
    "sync"
    )

    type A struct {
    name string
    mu sync.Mutex
    }
    func (a *A) Say(){
    a.mu.Lock()
    defer a.mu.Unlock()
    fmt.Printf("A: %v\n",a.name)
    }

    type B struct{
    A
    }
    func (b *B) Say(){
    fmt.Printf("B: %v\n",b.name)
    }


    func main() {
    a := A{name:"joe"}
    a.Say()
    b := B{a}
    b.Say()
    }



    b := B{a} 报错,请文有没有其他方式可以解决
    7 条回复    2020-12-21 20:03:31 +08:00
    chor02
        1
    chor02  
    OP
       2020-05-15 23:43:19 +08:00
    解决了,改用指针就可以
    janxin
        2
    janxin  
       2020-05-15 23:48:22 +08:00
    没有报错吧...有个提示修改?
    damingxing
        3
    damingxing  
       2020-05-15 23:51:12 +08:00
    没发现有问题呀
    chor02
        4
    chor02  
    OP
       2020-05-16 02:51:49 +08:00
    @janxin @damingxing https://play.golang.org/p/Z9V9du-qu8f 报了个 literal copies lock value from a: play.A contains sync.Mutex
    hercule
        5
    hercule  
       2020-05-16 10:38:48 +08:00 via iPhone
    互斥锁,复制是有问题 de
    damingxing
        6
    damingxing  
       2020-05-16 13:29:31 +08:00
    @chor02 受教了,以后全部用*sync.Mutex
    Pegasus
        7
    Pegasus  
       2020-12-21 20:03:31 +08:00
    @damingxing 理解错了吧,这里应该是用 A 的指针作为成员。不是说 要用 *sync.Mutex 。
    type B struct {
    *A
    }
    然后初始化用传进去指针。话说 V2EX 连个格式化代码功能都没有么
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2624 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 01:52 · PVG 09:52 · LAX 18:52 · JFK 21:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.