Can single defer func() be shared by other functions?

Can single defer func() be shared by other functions?

Content Index :

Can single defer func() be shared by other functions?
Tag : go , By : Verbal
Date : January 11 2021, 05:14 PM

it fixes the issue You can defer any function. Where that function is defined isn't important.
This is perfectly valid:
func foo() {
    // Do foo

func bar() {
    defer foo()
    // Do something before foo

func baz() {
    defer foo()
    // Do something else before foo
func foo() error {
    f, err := os.Open(...)
    if err != nil {
        return err
    defer f.Close() // "Close()" is obviously not defined here
    // do something with f

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to make method return value if panic happen and processed in defer func(){...}() in golang

Tag : go , By : clifton anderson
Date : March 29 2020, 07:55 AM
This might help you My function must return a string whatever success or panic. , Name your return parameter, then you can set it in the defer method:
func getDBStoreStatus() (replyMessage string) {
    defer func(){ 
        if err := recover(); err != nil {  
            replyMessage = "Error happend." 

    //do something to store row into DB
    db, err := sql.Open("mysql", "user1:password@/databaseName?charset=utf8") 
    newMessage, err := db.Prepare("INSERT .............
    res, err := newMessage.Exec(...........
    if err != nil { 
    replyMessage = "OK"
    return replyMessage
func c() (i int) {
    defer func() { i++ }()
    return 1
    if err != nil { 
        return "Error happend."

Go, is it possible to put defer in sub func

Tag : go , By : kameel
Date : March 29 2020, 07:55 AM
help you fix your problem I think I understand what you're asking. You want to know if a function can place a function on the defer stack of the caller. The answer to that is no. One possible solution to this is to have the function that wants to defer something return that function to the caller and have the caller do the defer. For example:
func test2() {
    r, cleanup := subc()
    defer cleanup()

func subc() (*Resource, func()) {
    r, err := Open("a")
    if err != nil {
        log.Fatalf("error opening 'a'\n")
    return r, func() { r.Close() }

When defer func evaluates its parameters

Tag : go , By : user123585
Date : March 29 2020, 07:55 AM
this one helps. Ok I just figured out. If you pass any parameters to the defer func (like the 2nd defer function above), those parameters are evaluated when the defer function is deferred, not when they are executed. That means in my example err is still nil and has not been assigned to a new error yet.
on the other hand, in 1st defer above, err is not a parameter, but a variable in function a, and when 1st defer is executed, it has already been assigned to a new error.

Does Azure functions Fan-out / Fan-in func always have better performance than just running a single function thread?

Tag : azure , By : janik
Date : March 29 2020, 07:55 AM
around this issue Obviously, if your activity to be executed multiple times is something lightweight (e.g. adding numbers), it's going to be faster to execute it just within the single Function without remote calls, queues, and leaving the process whatsoever.
Fan-out / Fan-in pattern is only valid for expensive computations or IO operations that can benefit from parallelization.

defer func not recover

Tag : go , By : Nathan Good
Date : March 29 2020, 07:55 AM
With these it helps A call to recover will only stop a panic when called directly from the deferred function. Here's the relevant text from the recover documentation:
Related Posts Related QUESTIONS :
  • Unable to unmarshal AWS SQS message in GO
  • When does a channel block a goroutine
  • Why code in loop not executed when I have two go-routines
  • Read uint8 from []byte without creating a bytes.Buffer
  • Args and passing args from position[1] (not position 0)
  • How to keep single AWS S3 session in app?
  • How to convert int16 to hex-encoded string in Golang
  • Not able to encrypt using public key in golang
  • Go 1.12 modules: local import in non-local import
  • How to set a constant to negative value in Go
  • how to add new currency support to golang.org/x/text/currency
  • HTTP PUT request handler using go
  • How to defer an anonymous function returned by a function
  • Correct way of handling an error when implementing Less()
  • golang time.Format() gives different results for the same unix timestamp
  • How to make a function received different type as a string
  • How to compile a golang program within the golang code?
  • Find location of Golang application
  • Created a type alias for big.Int - but I can't Set it using its pointer receiver?
  • Should a developer commit Go generated code?
  • Go atomic store followed by atomic load is behaving erratically across routines
  • Two go files having package declaration main inside a package
  • Will go get command update the package in my local machine
  • Is the following implementation making my code parallel?
  • Is it possible to┬ácompile go code without builtin library that can run on a machine without operating system
  • Can I use an pointer to "error" to catch the return error?
  • Constant global user type values in Go
  • shouldn't unreachable code after os.Exit be flagged
  • How expensive is os.Getenv?
  • Conditional (Dynamic) Struct Tags
  • How to get info about last called func in Go?
  • Golang not incrementing by 0.1
  • How to set unique at struct Beego
  • How to use go importer
  • Output from benchmem
  • Generic panic recovering in go programs
  • Should database connections be opened and closed in every CRUD method?
  • Migrating your App Engine app from Go 1.9 to Go 1.11
  • How can I get the user's AppData folder path with golang?
  • Does delve support hot swapping of changes or some variant?
  • Address of Function Receiver Varies Between Methods
  • How to parse variable depth arrays into a struct from JSON
  • Building a small Go program for MIPS with no hardware floating point (softfloat required)
  • Go Interface property is undefined
  • Same package name on different files
  • How to stream result from grpc-server and how to return result from goroutines grpc server-stream to pass result to api
  • Golang detect if in focus or minimized
  • golang undefined: Scanner
  • Re-insert into channel causing deadlock
  • Idiomatic way to represent one of/union in Go
  • Why doesn't "go get" install the package to GOPATH?
  • What does "safely escaped with Go syntax" mean?
  • Function TestMain didn't run
  • Is it safe to remove dictionary keys while iterating over it?
  • grpc-go over https: failed rpc error: code = Unavailable desc = transport is closing:
  • what is the meaning of go syntax struct {}{}
  • How to find dependency causing "Sirupsen/logrus" vs. "sirupsen/logrus" unexpected module path error?
  • Test whether a function was called
  • How to nest structures in Go
  • < operator in Go lang
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com