What is the problem you are trying to solve? Ie, why do you need to copy a structure that contains a mutex?
In my experience copying arbitrary structures is an anti pattern as you're only making a shallow copy of the contents. Maps, slices, channels, pointers and so on will still point to their original location. So, wanting to do a shallow copy is usually wrong, and wanting to make a deep copy is complex in the context of circular reference and types which are private.
Can you explain a bit more about the background of your question and maybe we can give a more useful answer.
Thanks
Dave
Pro: fast and easya.mu.Lock()b := *aa.mu.Unlock()b.mu.Unlock()
a.mu.Lock()b := *aa.mu.Unlock()
var b TheStructb.a = a.ab.b = a.b...
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
But why did you need to clone the structure? That's the root cause, not the copying of the mutex.
Because I needed a clone, and independent copy that could then be used independently of the first. This would not work if they had pointers whose contents were protected by the mutex, but this was not the case.One might ask why one would ever need fork or vfork :-)
--
type Foo struct {// The following values do not changefd *os.Filea int// mu protects s, which can be changedmu sync.Mutexs string}
Manlio,Logger is not an ideal example as you only want parts of it cloned (the buf field). I would not try to clone the Logger structure with a copy since I don't want a clone in the end, only want some field duplicated. As I mentioned, if you have a pointer whose contents are being guarded by the mutex, you would not want to copy the structure.
I wanted a shallow copy of everything other than the mutex. The mutex was not guarding any content that was being pointed to. Simple example:type Foo struct {// The following values do not changefd *os.Filea int// mu protects s, which can be changedmu sync.Mutexs string}The desire is to have a new Foo, just like the old one, but has an independent value of s, which has a setter, hence has a mutex.
package main
import ( "errors" "fmt" "sync")
type A struct { Lock sync.Mutex X int}
type B struct { A Y int}
func newA(x int) (A, error) { if x > 0 { return A{}, errors.New("x should not be positive") } return A{X: x}, nil}
func newB(x int, y int) (B, error) { a, err := newA(x) if err != nil { return B{}, err } return B{ A: a, Y: y, }, nil}
func main() { b, err := newB(-1, 3) fmt.Println(b.Y) fmt.Println(err)}
go tool vet test.go
test.go:32: literal copies lock value from a: main.A contains sync.Mutex