What does io.Closer.Close do?

967 views
Skip to first unread message

Ian Gudger

unread,
Aug 9, 2021, 9:13:30 PM8/9/21
to golang-nuts
io.Closer simply says "Closer is the interface that wraps the basic Close method," but does not document its Close method.

Effective Go says:
"There are a number of such names and it's productive to honor them and the function names they capture. Read, Write, Close, Flush, String and so on have canonical signatures and meanings. To avoid confusion, don't give your method one of those names unless it has the same signature and meaning." (https://golang.org/doc/effective_go#interface-names)
...but does not elaborate on what the canonical meanings are.

So what is the canonical meaning of a Close method?

Brian Candler

unread,
Aug 10, 2021, 2:46:12 AM8/10/21
to golang-nuts
It's for file-like objects that should be closed when they're no longer being used, in order to reclaim resources promptly.  The details depend on the underlying type, but see for example os.File.Close:

"Close closes the File, rendering it unusable for I/O. On files that support SetDeadline, any pending I/O operations will be canceled and return immediately with an error. Close will return an error if it has already been called."

jake...@gmail.com

unread,
Aug 10, 2021, 12:46:44 PM8/10/21
to golang-nuts
Just to clarify, the statement " Close will return an error if it has already been called"  on  os.File.Close is explicitly not the behavior guaranteed by io.Closer, which specifically states: " The behavior of Close after the first call is undefined. Specific implementations may document their own behavior."

My understanding is that this is the result of a historical oversight, but can not be changed now.

Ian Lance Taylor

unread,
Aug 10, 2021, 1:01:33 PM8/10/21
to Ian Gudger, golang-nuts
I would say that the canonical meaning is to indicate that the value
will no longer be used. After calling Close, further uses of the
value are invalid.

Ian
Reply all
Reply to author
Forward
0 new messages