• Methods and Interfaces Part3


    1.Stringers

    One of the most ubiquitous interfaces is Stringer defined by the fmt package.

    type Stringer interface {
        String() string
    }

    A Stringer is a type that can describe itself as a string. The fmt package (and many others) look for this interface to print values.

    1. package main
    2. import "fmt"
    3. type Person struct {
    4. Name string
    5. Age int
    6. }
    7. func (p Person) String() string {
    8. return fmt.Sprintf("%v (%v years)", p.Name, p.Age)
    9. }
    10. func main() {
    11. a := Person{"Arthur Dent", 42}
    12. z := Person{"Zaphod Beeblebrox", 9001}
    13. fmt.Println(a, z)
    14. }

    2.Exercise: Stringers

    Make the IPAddr type implement fmt.Stringer to print the address as a dotted quad.

    For instance, IPAddr{1, 2, 3, 4} should print as "1.2.3.4".

    1. package main
    2. import "fmt"
    3. type IPAddr [4]byte
    4. // TODO: Add a "String() string" method to IPAddr.
    5. func main() {
    6. hosts := map[string]IPAddr{
    7. "loopback": {127, 0, 0, 1},
    8. "googleDNS": {8, 8, 8, 8},
    9. }
    10. for name, ip := range hosts {
    11. fmt.Printf("%v: %v\n", name, ip)
    12. }
    13. }

    3.Errors

    Go programs express error state with error values.

    The error type is a built-in interface similar to fmt.Stringer:

    type error interface {
        Error() string
    }

    (As with fmt.Stringer, the fmt package looks for the error interface when printing values.)

    Functions often return an error value, and calling code should handle errors by testing whether the error equals nil.

    i, err := strconv.Atoi("42")
    if err != nil {
        fmt.Printf("couldn't convert number: %v\n", err)
        return
    }
    fmt.Println("Converted integer:", i)

    A nil error denotes success; a non-nil error denotes failure.

    1. package main
    2. import (
    3. "fmt"
    4. "time"
    5. )
    6. type MyError struct {
    7. When time.Time
    8. What string
    9. }
    10. func (e *MyError) Error() string {
    11. return fmt.Sprintf("at %v, %s",
    12. e.When, e.What)
    13. }
    14. func run() error {
    15. return &MyError{
    16. time.Now(),
    17. "it didn't work",
    18. }
    19. }
    20. func main() {
    21. if err := run(); err != nil {
    22. fmt.Println(err)
    23. }
    24. }

    4.Exercise: Errors

    Copy your Sqrt function from the earlier exercise and modify it to return an error value.

    Sqrt should return a non-nil error value when given a negative number, as it doesn't support complex numbers.

    Create a new type

    type ErrNegativeSqrt float64

    and make it an error by giving it a

    func (e ErrNegativeSqrt) Error() string

    method such that ErrNegativeSqrt(-2).Error() returns "cannot Sqrt negative number: -2".

    Note: A call to fmt.Sprint(e) inside the Error method will send the program into an infinite loop. You can avoid this by converting e first: fmt.Sprint(float64(e)). Why?

    Change your Sqrt function to return an ErrNegativeSqrt value when given a negative number.

    1. package main
    2. import (
    3. "fmt"
    4. )
    5. func Sqrt(x float64) (float64, error) {
    6. return 0, nil
    7. }
    8. func main() {
    9. fmt.Println(Sqrt(2))
    10. fmt.Println(Sqrt(-2))
    11. }

    5.Readers

    The io package specifies the io.Reader interface, which represents the read end of a stream of data.

    The Go standard library contains many implementations of this interface, including files, network connections, compressors, ciphers, and others.

    The io.Reader interface has a Read method:

    func (T) Read(b []byte) (n int, err error)

    Read populates the given byte slice with data and returns the number of bytes populated and an error value. It returns an io.EOF error when the stream ends.

    The example code creates a strings.Reader and consumes its output 8 bytes at a time.

    1. package main
    2. import (
    3. "fmt"
    4. "io"
    5. "strings"
    6. )
    7. func main() {
    8. r := strings.NewReader("Hello, Reader!")
    9. b := make([]byte, 8)
    10. for {
    11. n, err := r.Read(b)
    12. fmt.Printf("n = %v err = %v b =%v\n", n, err, b)
    13. fmt.Printf("b[:n] = %q\n", b[:n])
    14. if err == io.EOF {
    15. break
    16. }
    17. }
    18. }

    6 Images

    Package image defines the Image interface:

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

    Note: the Rectangle return value of the Bounds method is actually an image.Rectangle, as the declaration is inside package image.

    (See the documentation for all the details.)

    The color.Color and color.Model types are also interfaces, but we'll ignore that by using the predefined implementations color.RGBA and color.RGBAModel. These interfaces and types are specified by the image/color package

    1. package main
    2. import (
    3. "fmt"
    4. "image"
    5. )
    6. func main() {
    7. m := image.NewRGBA(image.Rect(0, 0, 100, 100))
    8. fmt.Println(m.Bounds())
    9. fmt.Println(m.At(0, 0).RGBA())
    10. }

  • 相关阅读:
    C语言实现带头双向循环链表
    让别人访问电脑本地
    基于MATLAB仿真设计无线充电系统
    简单易懂的Spring核心流程介绍
    RandomAccessFile读性能优化
    开源网安解决方案荣获四川数实融合创新实践优秀案例
    Linux21 --- 计算机网络基础概论(网络基本概念、网络分层模型、网络应用程序通信流程)
    Harmony 复杂图形自绘制
    如何在非spring环境中调用service中的方法
    chrome 插件开发指南
  • 原文地址:https://blog.csdn.net/u011868279/article/details/133744287