简体   繁体   中英

Is it enough to use blank identifier for http.Response to prevent memory leaks in Golang?

For example, I am making a post request and I don't need the response object at all.

_, err := http.Post(url, "", &buf)

Am I safe from memory leak in that case? Will the response.Body be drained for proper connection reuse? Or I need to do the usual defer resp.Body.Close() thing?

The application must close the response body to reclaim the resources used by the underlying network connection. To enable reuse of the underlying connection, the application must read the response body before closing.

Assigning the response to the blank identifier will not close the connection.

There are no side effects for assignments, including assignments to the blank identifier.

playground example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM