Interface Standard Library
func main(){
var buf bytes.buffer
fmt.Fprintf(os.Stdout,"Hello")
fmt.Fprintf(&buf,"World")
}
package fmt
/usr/local/Cellar/go/1.17.5/libexec/src/fmt/print.go
// These routines end in 'f' and take a format string.
// Fprintf formats according to a format specifier and writes to w.
// It returns the number of bytes written and any write error encountered.
func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
p := newPrinter()
p.doPrintf(format, a)
n, err = w.Write(p.buf)
p.free()
return
}
package io
/usr/local/Cellar/go/1.17.5/libexec/src/io/io.go
// Writer is the interface that wraps the basic Write method.
//
// Write writes len(p) bytes from p to the underlying data stream.
// It returns the number of bytes written from p (0 <= n <= len(p))
// and any error encountered that caused the write to stop early.
// Write must return a non-nil error if it returns n < len(p).
// Write must not modify the slice data, even temporarily.
//
// Implementations must not retain p.
type Writer interface {
Write(p []byte) (n int, err error)
}
package os
/usr/local/Cellar/go/1.17.5/libexec/src/os/file.go
// Write writes len(b) bytes to the File.
// It returns the number of bytes written and an error, if any.
// Write returns a non-nil error when n != len(b).
func (f *File) Write(b []byte) (n int, err error) {
if err := f.checkValid("write"); err != nil {
return 0, err
}
n, e := f.write(b)
if n < 0 {
n = 0
}
if n != len(b) {
err = io.ErrShortWrite
}
epipecheck(f, e)
if e != nil {
err = f.wrapErr("write", e)
}
return n, err
}
package bytes
/usr/local/Cellar/go/1.17.5/libexec/src/bytes/buffer.go
// Write appends the contents of p to the buffer, growing the buffer as
// needed. The return value n is the length of p; err is always nil. If the
// buffer becomes too large, Write will panic with ErrTooLarge.
func (b *Buffer) Write(p []byte) (n int, err error) {
b.lastRead = opInvalid
m, ok := b.tryGrowByReslice(len(p))
if !ok {
m = b.grow(len(p))
}
return copy(b.buf[m:], p), nil
}
io.Writter interface
- The io.Writter interface type is one of the most widely used interfaces.
- It provides an abstraction of all the types to which byes can be written, which includes
- Files
- Memory buffers
- Network connections
- HTTP clients
Other interface type in package io
type Reader interface {
Read(p []byte) (n int, err error)
}
type Closer interface {
Close() error
}
type ReadWriter interface {
Reader
Writer
}
type ReadWriteCloser interface {
Reader
Writer
Closer
}
Stringer interface
/usr/local/Cellar/go/1.17.5/libexec/src/fmt/print.go
type Stringer interface {
String() string
}
- Stringer interface provides a way for types to control hoe their values are printed.
- The fmt package functions(Println, Fprintln,...) checks if concrete type has string method, if it does, then they call string method of the type to format values.