Skip to content

Instantly share code, notes, and snippets.

@asukakenji
Last active April 19, 2024 11:13
Show Gist options
  • Save asukakenji/ac8a05644a2e98f1d5ea8c299541fce9 to your computer and use it in GitHub Desktop.
Save asukakenji/ac8a05644a2e98f1d5ea8c299541fce9 to your computer and use it in GitHub Desktop.
Go (Golang) Standard Library Interfaces (Selected)

Go (Golang) Standard Library Interfaces (Selected)

This is not an exhaustive list of all interfaces in Go's standard library. I only list those I think are important. Interfaces defined in frequently used packages (like io, fmt) are included. Interfaces that have significant importance are also included.

All of the following information is based on go version go1.8.3 darwin/amd64.

(builtin)

error [doc] [src1] [src2]

type error interface {
	Error() string
}

package runtime

Error [doc] [src1] [src2]

type Error interface {
	error
	RuntimeError()
}

package math/rand

Source [doc] [src1] [src2]

type Source interface {
	Int63() int64
	Seed(seed int64)
}

Source64 [doc] [src1] [src2]

type Source64 interface {
	Source
	Uint64() uint64
}

package sort

Interface [doc] [src1] [src2]

type Interface interface {
	Len() int
	Less(i, j int) bool
	Swap(i, j int)
}

package container/heap

Interface [doc] [src1] [src2]

type Interface interface {
	sort.Interface
	Push(x interface{})
	Pop() interface{}
}

package io

Reader [doc] [src1] [src2]

type Reader interface {
	Read(p []byte) (n int, err error)
}

Writer [doc] [src1] [src2]

type Writer interface {
	Write(p []byte) (n int, err error)
}

Closer [doc] [src1] [src2]

type Closer interface {
	Close() error
}

Seeker [doc] [src1] [src2]

type Seeker interface {
	Seek(offset int64, whence int) (int64, error)
}

ReadWriter [doc] [src1] [src2]

type ReadWriter interface {
	Reader
	Writer
}

ReadCloser [doc] [src1] [src2]

type ReadCloser interface {
	Reader
	Closer
}

WriteCloser [doc] [src1] [src2]

type WriteCloser interface {
	Writer
	Closer
}

ReadWriteCloser [doc] [src1] [src2]

type ReadWriteCloser interface {
	Reader
	Writer
	Closer
}

ReadSeeker [doc] [src1] [src2]

type ReadSeeker interface {
	Reader
	Seeker
}

WriteSeeker [doc] [src1] [src2]

type WriteSeeker interface {
	Writer
	Seeker
}

ReadWriteSeeker [doc] [src1] [src2]

type ReadWriteSeeker interface {
	Reader
	Writer
	Seeker
}

ReaderFrom [doc] [src1] [src2]

type ReaderFrom interface {
	ReadFrom(r Reader) (n int64, err error)
}

WriterTo [doc] [src1] [src2]

type WriterTo interface {
	WriteTo(w Writer) (n int64, err error)
}

ReaderAt [doc] [src1] [src2]

type ReaderAt interface {
	ReadAt(p []byte, off int64) (n int, err error)
}

WriterAt [doc] [src1] [src2]

type WriterAt interface {
	WriteAt(p []byte, off int64) (n int, err error)
}

ByteReader [doc] [src1] [src2]

type ByteReader interface {
	ReadByte() (byte, error)
}

ByteScanner [doc] [src1] [src2]

type ByteScanner interface {
	ByteReader
	UnreadByte() error
}

ByteWriter [doc] [src1] [src2]

type ByteWriter interface {
	WriteByte(c byte) error
}

RuneReader [doc] [src1] [src2]

type RuneReader interface {
	ReadRune() (r rune, size int, err error)
}

RuneScanner [doc] [src1] [src2]

type RuneScanner interface {
	RuneReader
	UnreadRune() error
}

package fmt

State [doc] [src1] [src2]

type State interface {
	Write(b []byte) (n int, err error)
	Width() (wid int, ok bool)
	Precision() (prec int, ok bool)
	Flag(c int) bool
}

Formatter [doc] [src1] [src2]

type Formatter interface {
	Format(f State, c rune)
}

Stringer [doc] [src1] [src2]

type Stringer interface {
	String() string
}

GoStringer [doc] [src1] [src2]

type GoStringer interface {
	GoString() string
}

ScanState [doc] [src1] [src2]

type ScanState interface {
	ReadRune() (r rune, size int, err error)
	UnreadRune() error
	SkipSpace()
	Token(skipSpace bool, f func(rune) bool) (token []byte, err error)
	Width() (wid int, ok bool)
	Read(buf []byte) (n int, err error)
}

Scanner [doc] [src1] [src2]

type Scanner interface {
	Scan(state ScanState, verb rune) error
}

package encoding

BinaryMarshaler [doc] [src1] [src2]

type BinaryMarshaler interface {
	MarshalBinary() (data []byte, err error)
}

BinaryUnmarshaler [doc] [src1] [src2]

type BinaryUnmarshaler interface {
	UnmarshalBinary(data []byte) error
}

TextMarshaler [doc] [src1] [src2]

type TextMarshaler interface {
	MarshalText() (text []byte, err error)
}

TextUnmarshaler [doc] [src1] [src2]

type TextUnmarshaler interface {
	UnmarshalText(text []byte) error
}

package net

Addr [doc] [src1] [src2]

type Addr interface {
	Network() string
	String() string
}

Conn [doc] [src1] [src2]

type Conn interface {
	Read(b []byte) (n int, err error)
	Write(b []byte) (n int, err error)
	Close() error
	LocalAddr() Addr
	RemoteAddr() Addr
	SetDeadline(t time.Time) error
	SetReadDeadline(t time.Time) error
	SetWriteDeadline(t time.Time) error
}

PacketConn [doc] [src1] [src2]

type PacketConn interface {
	ReadFrom(b []byte) (n int, addr Addr, err error)
	WriteTo(b []byte, addr Addr) (n int, err error)
	Close() error
	LocalAddr() Addr
	SetDeadline(t time.Time) error
	SetReadDeadline(t time.Time) error
	SetWriteDeadline(t time.Time) error
}

Listener [doc] [src1] [src2]

type Listener interface {
	Accept() (Conn, error)
	Close() error
	Addr() Addr
}

Error [doc] [src1] [src2]

type Error interface {
	error
	Timeout() bool
	Temporary() bool
}

package net/http

RoundTripper [doc] [src1] [src2]

type RoundTripper interface {
	RoundTrip(*Request) (*Response, error)
}

FileSystem [doc] [src1] [src2]

type FileSystem interface {
	Open(name string) (File, error)
}

File [doc] [src1] [src2]

type File interface {
	io.Closer
	io.Reader
	io.Seeker
	Readdir(count int) ([]os.FileInfo, error)
	Stat() (os.FileInfo, error)
}

Pusher [doc] [src1] [src2]

type Pusher interface {
	Push(target string, opts *PushOptions) error
}

CookieJar [doc] [src1] [src2]

type CookieJar interface {
	SetCookies(u *url.URL, cookies []*Cookie)
	Cookies(u *url.URL) []*Cookie
}

Handler [doc] [src1] [src2]

type Handler interface {
	ServeHTTP(ResponseWriter, *Request)
}

ResponseWriter [doc] [src1] [src2]

type ResponseWriter interface {
	Header() Header
	Write([]byte) (int, error)
	WriteHeader(int)
}

Flusher [doc] [src1] [src2]

type Flusher interface {
	Flush()
}

Hijacker [doc] [src1] [src2]

type Hijacker interface {
	Hijack() (net.Conn, *bufio.ReadWriter, error)
}

CloseNotifier [doc] [src1] [src2]

type CloseNotifier interface {
	CloseNotify() <-chan bool
}

package image

Image [doc] [src1] [src2]

type Image interface {
	ColorModel() color.Model
	Bounds() Rectangle
	At(x, y int) color.Color
}

PalettedImage [doc] [src1] [src2]

type PalettedImage interface {
	ColorIndexAt(x, y int) uint8
	Image
}

package image/color

Color [doc] [src1] [src2]

type Color interface {
	RGBA() (r, g, b, a uint32)
}

Model [doc] [src1] [src2]

type Model interface {
	Convert(c Color) Color
}

package image/draw

Image [doc] [src1] [src2]

type Image interface {
	image.Image
	Set(x, y int, c color.Color)
}

Quantizer [doc] [src1] [src2]

type Quantizer interface {
	Quantize(p color.Palette, m image.Image) color.Palette
}

Drawer [doc] [src1] [src2]

type Drawer interface {
	Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point)
}

package hash

Hash [doc] [src1] [src2]

type Hash interface {
	io.Writer
	Sum(b []byte) []byte
	Reset()
	Size() int
	BlockSize() int
}

Hash32 [doc] [src1] [src2]

type Hash32 interface {
	Hash
	Sum32() uint32
}

Hash64 [doc] [src1] [src2]

type Hash64 interface {
	Hash
	Sum64() uint64
}

package crypto

Signer [doc] [src1] [src2]

type Signer interface {
	Public() PublicKey
	Sign(rand io.Reader, digest []byte, opts SignerOpts) (signature []byte, err error)
}

SignerOpts [doc] [src1] [src2]

type SignerOpts interface {
	HashFunc() Hash
}

Decrypter [doc] [src1] [src2]

type Decrypter interface {
	Public() PublicKey
	Decrypt(rand io.Reader, msg []byte, opts DecrypterOpts) (plaintext []byte, err error)
}

package reflect

Type [doc] [src1] [src2]

type Type interface {
	Align() int
	FieldAlign() int
	Method(int) Method
	MethodByName(string) (Method, bool)
	NumMethod() int
	Name() string
	PkgPath() string
	Size() uintptr
	String() string
	Kind() Kind
	Implements(u Type) bool
	AssignableTo(u Type) bool
	ConvertibleTo(u Type) bool
	Comparable() bool
	Bits() int
	ChanDir() ChanDir
	IsVariadic() bool
	Elem() Type
	Field(i int) StructField
	FieldByIndex(index []int) StructField
	FieldByName(name string) (StructField, bool)
	FieldByNameFunc(match func(string) bool) (StructField, bool)
	In(i int) Type
	Key() Type
	Len() int
	NumField() int
	NumIn() int
	NumOut() int
	Out(i int) Type
	common() *rtype
	uncommon() *uncommonType
}

package os

Signal [doc] [src1] [src2]

type Signal interface {
	String() string
	Signal()
}

FileInfo [doc] [src1] [src2]

type FileInfo interface {
	Name() string
	Size() int64
	Mode() FileMode
	ModTime() time.Time
	IsDir() bool
	Sys() interface{}
}

Source

iface.awk

BEGIN {
    if (package == "") {
        print "error: package is not defined"
        exit 1
    }

    if (branch == "") {
        print "error: branch is not defined"
        exit 1
    }

    state = 0
    indent0 = 0
    indent1 = 0
    from_line = 0
    to_line = 0
    filename = ""
    type = ""
    code = ""

    printf "\n"
    printf "\n"
    printf "\n"
    if (package == "builtin") {
        printf "### (builtin)\n"
    } else {
        printf "### package `%s`\n", package
    }
}

# Start of type
/type ([A-Z][^ ]*|error) interface {/ {
    if (state == 0) {
        indent0 = index($0, "type ")
        if (indent0 == 1) {
            state = 1

            s = substr($0, indent0 + 5) # length("type ") == 5
            len = index(s, " ") - 1
            type = substr(s, 0, len)

            filename = FILENAME
            sub(/.*\//, "", filename)

            from_line = FNR
            code = ""
        } else {
            # >>> Uncomment this block to write an alert instead of skipping the code <<<
            # state = 1
            #
            # s = substr($0, indent0 + 5) # length("type ") == 5
            # len = index(s, " ") - 1
            # type = substr(s, 0, len)
            #
            # filename = FILENAME
            # sub(/.*\//, "", filename)
            #
            # from_line = FNR
            # code = ""
            #
            # printf "\n# type is not the first character: filename: %s line: %d\n\n", FILENAME, FNR
        }
    }
}

# Inside type
{
    if (state == 1) {
        line = $0
        # Remove comments
        sub(/[\t ]*\/\/.*/, "", line)
        # Remove trailing whitespaces
        sub(/[\t ]*$/, "", line)
        # Only print non-blank lines
        if (line != "") {
            code = code line "\n"
        }
    }
}

# End of type
/}/ {
    if (state == 1) {
        indent1 = index($0, "}")
        if (indent0 == indent1) {
            state = 0
            to_line = FNR
            printf "\n"
            printf "#### %s " \
                "[[doc](https://golang.org/pkg/%s/#%s)] " \
                "[[src1](https://golang.org/src/%s/%s#L%d)] " \
                "[[src2](https://github.com/golang/go/blob/release-branch.%s/src/%s/%s#L%d-L%d)]\n",
                type,
                package, type,
                package, filename, from_line,
                branch, package, filename, from_line, to_line
            printf "\n"
            printf "```go\n"
            printf "%s", code
            printf "```\n"
        }
    }
}

make.sh

#!/bin/sh

packages=(
    'builtin'
    'runtime'
    'math/rand'
    'sort'
    'container/heap'
    'io'
    'fmt'
    'encoding'
    'net'
    'net/http'
    'image'
    'image/color'
    'image/draw'
    'hash'
    'crypto'
    'reflect'
    'os'
)

if [ -z "${GOROOT}" ]
then
    eval $(go env | grep -e '^GOROOT=')
fi

if [ -z "${GOROOT}" ]
then
    echo 'Cannot find GOROOT'
    exit 1
fi

go_version=$(go version)
go_branch=${go_version#go version }
go_branch=${go_branch% *}

case ${go_branch} in
go[0-9].[0-9])
    ;;
go[0-9].[0-9].[0-9])
    go_branch=${go_branch%.[0-9]}
    ;;
*)
    printf 'Unexpected go version: %s\n' ${go_version}
    exit 2
    ;;
esac

echo '# Go (Golang) Standard Library Interfaces (Selected)'
echo
echo "This is not an exhaustive list of all interfaces in Go's standard library."
echo 'I only list those I think are important.'
echo 'Interfaces defined in frequently used packages (like `io`, `fmt`) are included.'
echo 'Interfaces that have significant importance are also included.'
echo
printf 'All of the following information is based on `%s`.\n' "$(go version)"

for package in ${packages[@]}
do
    find ${GOROOT}/src/${package} -maxdepth 1 \
        -type f '(' \
            -name '*_test.go' -prune -o \
            -name '*.go' -exec \
                awk -f iface.awk -v package="${package}" -v branch="${go_branch}" '{}' '+' \
        ')'
done

printf '\n'
printf '\n'
printf '\n'
printf '\n'
printf '\n'
printf '## Source\n'
printf '\n'

printf '### iface.awk\n'
printf '\n'
printf '```awk\n'
cat iface.awk
printf '```\n'
printf '\n'

printf '### make.sh\n'
printf '\n'
printf '```sh\n'
cat make.sh
printf '```\n'
@baxiry
Copy link

baxiry commented Aug 9, 2019

Very useful . Thank you so much

@ianjuma
Copy link

ianjuma commented Feb 5, 2020

thank you , this was helpful

@mattypiper
Copy link

I suggest adding json.Marshaler and json.Unmarshaler

type Marshaler interface {
    MarshalJSON() ([]byte, error)
}

type Unmarshaler interface {
    UnmarshalJSON([]byte) error
}

@kagxin
Copy link

kagxin commented Sep 30, 2020

database/sql

type Scanner interface {
	Scan(src interface{}) error
}
type Valuer interface {
	Value() (Value, error)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment