fork download
  1. package main
  2.  
  3. import "fmt"
  4.  
  5. type file struct {
  6. name string
  7. exist bool
  8. openned bool
  9. writable bool
  10. }
  11.  
  12. func (f *file) open() {
  13. if !f.exist {
  14. panic("file does not exist!")
  15. }
  16. if f.openned {
  17. return
  18. }
  19. f.openned = true
  20. fmt.Println(f.name + ": openned")
  21. }
  22.  
  23. func (f *file) write(data string) {
  24. if !f.openned {
  25. panic("can not write to closed file!")
  26. }
  27. if !f.writable {
  28. panic("can not write to file: permission denied!")
  29. }
  30. fmt.Println(f.name + ": writed: " + data)
  31. }
  32.  
  33. func (f *file) close() {
  34. if f.openned {
  35. f.openned = false
  36. fmt.Println(f.name + ": closed")
  37. }
  38. }
  39.  
  40. // --------------------------------
  41.  
  42. func (f *file) onOpenError() {
  43. if r := recover(); r != nil {
  44. fmt.Println(f.name + ":", r)
  45. }
  46. }
  47.  
  48. func (f *file) onWriteError() {
  49. if r := recover(); r != nil {
  50. fmt.Println(f.name + ":", r)
  51. }
  52. }
  53.  
  54. // --------------------------------
  55.  
  56. func makeTest(name string, exist bool, writable bool) func() {
  57. return func() {
  58. f := &file{name: name, exist: exist, openned: false, writable: writable}
  59.  
  60. defer f.onOpenError()
  61. f.open()
  62.  
  63. defer f.close()
  64. defer f.onWriteError()
  65. f.write("Hello!")
  66. }
  67. }
  68.  
  69. var tests = []func(){
  70. makeTest("test1", false, false),
  71. makeTest("test2", false, true),
  72. makeTest("test3", true, false),
  73. makeTest("test4", true, true),
  74. }
  75.  
  76. func main() {
  77. for _, test := range tests {
  78. fmt.Println("--------------------------------")
  79. test()
  80. }
  81. }
  82.  
Success #stdin #stdout 0.02s 2416KB
stdin
Standard input is empty
stdout
--------------------------------
test1: file does not exist!
--------------------------------
test2: file does not exist!
--------------------------------
test3: openned
test3: can not write to file: permission denied!
test3: closed
--------------------------------
test4: openned
test4: writed: Hello!
test4: closed