File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -134,6 +134,11 @@ concepts:
134134 test_regex : " .*"
135135 hints :
136136 - Define a custom error type and return it from a function.
137+ - slug : 28_defer
138+ title : Deferred Execution
139+ test_regex : " .*"
140+ hints :
141+ - Close the file using `defer` keyword with f.Close().
137142
138143projects :
139144- slug : 101_text_analyzer
Original file line number Diff line number Diff line change 1+ package deferr
2+
3+ import (
4+ "fmt"
5+ "os"
6+ )
7+
8+ func WriteToFile (* os.File ) {
9+ f := CreateFile ()
10+ defer f .Close ()
11+ fmt .Fprintln (f , "data" )
12+ }
Original file line number Diff line number Diff line change 1+ package deferr
2+
3+ import (
4+ "fmt"
5+ "os"
6+ )
7+
8+ func WriteToFile (* os.File ) {
9+ f := CreateFile ()
10+ fmt .Fprintln (f , "ABC" )
11+ }
Original file line number Diff line number Diff line change 1+ package deferr
2+
3+ import (
4+ "fmt"
5+ "testing"
6+ )
7+
8+ func TestClosingFileAfterWriting (t * testing.T ) {
9+ f := CreateFile ()
10+ WriteToFile (f )
11+
12+ // Trying to write to the file after closing
13+ _ , err := fmt .Fprintln (f , "123" )
14+ if err == nil {
15+ t .Fatal ("File wasn't closed!" )
16+ }
17+ }
Original file line number Diff line number Diff line change 1+ package deferr
2+
3+ import (
4+ "os"
5+ "sync"
6+ )
7+
8+ var (
9+ fileInstance * os.File
10+ once sync.Once
11+ )
12+
13+ // Create a singleton of a temporary file
14+ func CreateFile () * os.File {
15+ once .Do (func () {
16+ f , err := os .CreateTemp ("" , "tmpfile" )
17+ if err != nil {
18+ panic (err )
19+ }
20+ fileInstance = f
21+ })
22+ return fileInstance
23+ }
You can’t perform that action at this time.
0 commit comments