Interface examples with type elements
April 26, 2023
Let’s look at some interface examples from the spec:
General interfaces
…
// An interface representing only the type int. interface { int } // An interface representing all types with underlying type int. interface { ~int } // An interface representing all types with underlying type int that implement the String method. interface { ~int String() string } // An interface representing an empty type set: there is no type that is both an int and a string. interface { int string }
These examples should be pretty self-documenting. But let’s consider an imaginary example of the third case, as that may be the most interesting.
Let’s consider the HTTP status constants in the net/http
package. Although these are untyped constants, we could easily imagine a custom type for these, perhaps defined in our own package:
type HTTPStatus int
const (
StatusContinue = HTTPStatus(100) // RFC 9110, 15.2.1
StatusSwitchingProtocols = HTTPStatus(101) // RFC 9110, 15.2.2
StatusProcessing = HTTPStatus(102) // RFC 2518, 10.1
StatusEarlyHints = HTTPStatus(103) // RFC 8297
StatusOK = HTTPStatus(200) // RFC 9110, 15.3.1
StatusCreated = HTTPStatus(201) // RFC 9110, 15.3.2
/* etc ... */
)
// String() returns a text for the HTTP status code. It returns the empty
// string if the code is unknown.
func (s HTTPStatus) String() string {
return http.StatusText(s)
}
Quotes from The Go Programming Language Specification Version of December 15, 2022