It's not pretty, but if you absolutely must write this code and can't refactor 
it, you can always use a closure to scope the defer:

lock1.Lock()
err = func() error {
  defer lock1.Unlock()
  return performOperation1()
}()
if err != nil {
  return err
}
performExpensiveOperation2()

On Fri, Feb 8, 2019, at 18:28, vincent163 wrote:
> I am thinking about how to write programs like this:
> `
> lock1.Lock()
> err = performOperation1()
> if err != nil {
>  lock1.Unlock()
>  return err
> }
> lock1.Unlock()
> performExpensiveOperation2()
> `
> 
> The lock1 must be locked while performing operation1, and I need to use 
> its result to perform operation2. Since operation2 is expensive, I 
> don't want to hold the lock while performing it, and lock1.Unlock() 
> needs to be called before calling operation2.
> Go's defer mechanism doesn't seem to handle this case well since the 
> resource is used only within a block and not throughout the function. 
> Is there a recommended way to write programs in this case?
> I know I could wrap the lock block in a closure, but that creates a 
> completely new scope, so I can't return directly or break out of a loop 
> within the closure, etc.
>  
> 
> 
>  -- 
>  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+unsubscr...@googlegroups.com.
>  For more options, visit https://groups.google.com/d/optout.
>

-- 
Sam Whited

-- 
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+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to