The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
chor02

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

  •  
  •   chor02 · May 15, 2020 · 5209 views
    This topic created in 2191 days ago, the information mentioned may be changed or developed.
    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 replies    2020-12-21 20:03:31 +08:00
    chor02
        1
    chor02  
    OP
       May 15, 2020
    解决了,改用指针就可以
    janxin
        2
    janxin  
       May 15, 2020
    没有报错吧...有个提示修改?
    damingxing
        3
    damingxing  
       May 15, 2020
    没发现有问题呀
    chor02
        4
    chor02  
    OP
       May 16, 2020
    @janxin @damingxing https://play.golang.org/p/Z9V9du-qu8f 报了个 literal copies lock value from a: play.A contains sync.Mutex
    hercule
        5
    hercule  
       May 16, 2020 via iPhone
    互斥锁,复制是有问题 de
    damingxing
        6
    damingxing  
       May 16, 2020
    @chor02 受教了,以后全部用*sync.Mutex
    Pegasus
        7
    Pegasus  
       Dec 21, 2020
    @damingxing 理解错了吧,这里应该是用 A 的指针作为成员。不是说 要用 *sync.Mutex 。
    type B struct {
    *A
    }
    然后初始化用传进去指针。话说 V2EX 连个格式化代码功能都没有么
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   870 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 45ms · UTC 21:13 · PVG 05:13 · LAX 14:13 · JFK 17:13
    ♥ Do have faith in what you're doing.