go lang defer close
时间: 2023-11-18 18:12:31 浏览: 42
In Go language, the `defer` statement is used to schedule a function call to be executed at the end of the current function, but before it returns. This is often used to ensure that resources are released or other cleanup tasks are performed regardless of whether an error is encountered or not.
For example, let's say you have opened a file in a function and you want to make sure that the file is closed before the function returns, you can use `defer` statement to close the file:
```
func readFromFile(filename string) error {
f, err := os.Open(filename)
if err != nil {
return err
}
defer f.Close() // ensure file is closed before function returns
// read from file
// ...
return nil
}
```
In this example, the `f.Close()` function call is scheduled to be executed at the end of the `readFromFile` function, but before it returns, regardless of whether an error is encountered or not.
Now, let's talk about `close` statement. In Go, channels can be closed using the `close` function. A closed channel indicates that no more values will be sent to it. Receiving from a closed channel will return the zero value for the channel's type.
Here's an example of closing a channel using the `close` function:
```
ch := make(chan int)
go func() {
for i := 0; i < 5; i++ {
ch <- i
}
close(ch)
}()
for v := range ch {
fmt.Println(v)
}
```
In this example, a new goroutine is launched to send values to the channel `ch`. After sending 5 values, the channel is closed using the `close` function. Then, in the main goroutine, values are received from the channel using a `for range` loop until the channel is closed.