[Golang] How To Work With Defer In Golang Tutorial
Today we are going to learn about defer in golang. What Defer does and how it works we are going to see that via implementation of some code which is focused on defer keyword of golang.
So before starting let's understand the defer via it's definition then we are going to implement some code on it.
What if Defer?
Defer statement is used to execute a function call just before the surrounding function where the defer statement is present returns.The definition might seem complex but it's pretty simple to understand by means of an example.
We have finished the definition reading part and via it we understand that a defer runs before exiting or returning from a function, means the last second last step of function which have defer keyword used.
Now let's write some code to understand it in via code.
EXAMPLE
package mainimport ("fmt")func sliceToName(s []string) {var str stringfmt.Println("Started joining slice into string")for _, is := range s {str += is}fmt.Println("Create name from slice is", str)}func main() {defer fmt.Println("Finished joining slice into string")s := []string{"G", "O", "L", "A", "N", "G"}sliceToName(s)}
The above code is a simple program to combine the slice of string into a single string to make it a full name.I know I can use the join function as well from the string package but for testing we decided to make our own.The sliceToName function takes a string slice as a function parameter and prints the combined values of a slice into string. The most important line is defer which we have in our main function as you can see we have used fmt.Println as before that we have added defer keyword in it so now let's run the code and the sequence of the code execution.
Started joining slice into string
Create name from slice is GOLANG
Finished joining slice into string
package mainimport ("fmt")func DeferedFinished() {fmt.Println("Finished joining slice into string")}func sliceToName(s []string) {defer DeferedFinished()var str stringfmt.Println("Started joining slice into string")for _, is := range s {str += is}fmt.Println("Create name from slice is", str)}func main() {s := []string{"G", "O", "L", "A", "N", "G"}sliceToName(s)}
Started joining slice into string
Create name from slice is GOLANG
Finished joining slice into string
Multiple Defer Keywords Case
EXAMPLE 1
package mainimport ("fmt")func deferSequence(i int) {fmt.Println("Defer Sequence Number", i)}func main() {deferSequence(5)deferSequence(4)deferSequence(3)deferSequence(2)deferSequence(1)}
Defer Sequence Number 5
Defer Sequence Number 4
Defer Sequence Number 3
Defer Sequence Number 2
Defer Sequence Number 1
EXAMPLE 2
package mainimport ("fmt")func deferSequence(i int) {fmt.Println("Defer Sequence Number", i)}func main() {defer deferSequence(5)defer deferSequence(4)defer deferSequence(3)defer deferSequence(2)defer deferSequence(1)}
Defer Sequence Number 1
Defer Sequence Number 2
Defer Sequence Number 3
Defer Sequence Number 4
Defer Sequence Number 5
Uses Defer to close files as well
EXAMPLE
package mainimport ("fmt""os")func isError(err error) bool {if err != nil {fmt.Println(err.Error())}return (err != nil)}func main() {var path = "app.txt"fmt.Println("Opening a file ")var file, err = os.OpenFile(path, os.O_RDWR, 0644)if isError(err) {return}defer file.Close()}
Using Defer in Loop.
package mainimport ("fmt")func main() {name := "Kuldeep"fmt.Printf("Original String: %s\n", name)fmt.Printf("Reversed String: ")for _, v := range []rune(name) {defer fmt.Printf("%c", v)}}
Original String: Kuldeep
Reversed String: peedluK
Labels: Golang
0 Comments:
Post a Comment
If have any queries lemme know
Subscribe to Post Comments [Atom]
<< Home