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

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

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