SoFunction
Updated on 2025-03-01

GO language Defer usage example analysis

/**
 * Created with IntelliJ IDEA.
 * To change this template use File | Settings | File Templates.
 * Name:Defer
 */
package main
import (
 "fmt"
 "os"
 "log"
 "io"
)
//Return the file content as a string
func Contents(filename string) (string) {
//Open the file
 f, err := (filename)
 if err != nil {
  ("%s",err)
 }
("Previous >",f)
// If it is finished when executing here. So use DEFER to delay execution
// He should execute it after receiving () (I personally understand)
 defer ()
("Close after>",f)
 var result []byte
 buf := make([]byte, 100)
 for {
  n, err := (buf[0:])
  result = append(result, buf[0:n]...)
  if err != nil {
   if err == {
    break
   }
("Fixed f>%s without receiving",err) // If f is closed in advance, print
  }
 }
 return string(result)
}
func main() {

 fileurl := ("HOME")
 filename := fileurl+"/"
 (Contents(filename))
}