package main import ( "fmt" "os" ) func main() { // Open file file, err := os.Open("example.txt") if err != nil { fmt.Println(err) return } defer file.Close() // Close file }
package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" ) func main() { // Open database connection db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/test_db") if err != nil { fmt.Println(err) return } defer db.Close() // Close database connection }In this example, we open a database connection to MySQL using sql.Open and check for any errors. If there is no error, we use the defer statement to schedule the database connection to be closed when the function returns. The io.Closer Close method is part of the standard Go library and can be found in the "io" package.