Last active
February 21, 2019 19:15
-
-
Save leosabbir/8841a84e66bd16c0693e9f8b2f3c769c to your computer and use it in GitHub Desktop.
illustrate defer for receiver being nil at later point.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type Data struct { | |
name string | |
} | |
func (d *Data) String() string { | |
return fmt.Sprintf("Name: %s", d.name) | |
} | |
func (d *Data) Print() { | |
fmt.Println(d) | |
} | |
func main() { | |
ss := &Data{"Giney"} | |
defer ss.Print() | |
ss = &Data{"Hermionie"} // Expect to see: Name: Hermione | |
fmt.Println(ss) | |
ss = nil | |
fmt.Println(ss) // Expect to see: <nil> | |
// Since the method is going to return here, it will execute deferred method ss.Print(). | |
// At this point ss is nil. | |
// So what will happen here??? ERROR?? | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment