I think it would be problematic, as the callee signature is limited - func() 
error - and with lack of method overloading you will need a lot of WithXXXX 
methods…

> On Sep 12, 2018, at 6:58 AM, Mirko Friedenhagen <mfriedenha...@gmx.de> wrote:
> 
> Hello,
> 
> in Python I may define context managers which do stuff before and after an 
> action has taken place.
> 
> E.g.:
> 
> ```
> class MyContext(object):
>     def __enter__(self):
>         print("Entering context")
>     def __exit__(self, extype_unused, value_unused, traceback_unused):
>         print("Exiting context")
> 
> if __name__ == "__main__":
>     with MyContext():
>         print("Inside the context")
> ```
> 
> will print:
> Entering context
> Inside the context
> Exiting context
> 
> A Golang equivalent I came up with is something like (see 
> https://play.golang.org/p/epBGtwZWuln as well)
> 
> ```
> package main
> 
> import "log"
> 
> type Context interface {
>       __entry__()
>       __exit__()
> }
> 
> func WithContext(context Context, f func() error) error {
>       context.__entry__()
>       defer context.__exit__()
>       return f()
> }
> 
> type MyContext struct {
>       message string
> }
> 
> func (context *MyContext) __entry__() {
>       log.Print("Entering ", context.message)
> }
> 
> func (context *MyContext) __exit__() {
>       log.Print("Exiting ", context.message)
> }
> 
> func main() {
>       var a string
>       WithContext(&MyContext{"Hallo"}, func() error {
>               log.Print("Inside context")
>               a = "Var from context"
>               return nil
>       })
>       log.Print(a)
> }
> ```
> 
> Is this idiomatic or are there better ways to implement stuff like this?
> 
> Regards
> Mirko
> 
> 
> -- 
> 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 
> <mailto:golang-nuts+unsubscr...@googlegroups.com>.
> For more options, visit https://groups.google.com/d/optout 
> <https://groups.google.com/d/optout>.

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