1
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?

4
  • Why are you embedding a reference? Commented Jul 16, 2014 at 17:09
  • @rvignacio: there's nothing particularly wrong with embedding a pointer to a struct. It might be more convenient if that embedded type is always referenced via a pointer, so you don't need to selectively dereference it or worry about inadvertently creating copies. Commented Jul 16, 2014 at 17:40
  • @JimB, I thought so at first, but there seems to be no difference between embedding by reference or value (I believe the runtime resolves the derreferencing)... I'm going to write a question about that =P Commented Jul 16, 2014 at 20:04
  • @rvignacio I thought embedding by instance will cause a copy? Please correct me if I am wrong. Can you post your question link to here? Commented Jul 16, 2014 at 21:17

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Embedded structs can be named, which suggests this method

f := &fun{}
s := starcraft{fun:f}

Which might be what you want

Playground

1 Comment

thanks this is also a good answer, accepted JimB's for more information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.