当前位置:网站首页>Original error interface

Original error interface

2022-06-12 17:37:00 Erya preaches Buddhism

1, summary .

Go The language introduces a standard pattern for error handling , namely error Interface , It is Go The type of interface built into the language , This interface is defined as follows :

type error interface {
    Error() string
}

Go Standard library code package for languages errors Provide users with the following methods :

package errors

type errorString struct { 
    text string 
}

func New(text string) error { 
    return &errorString{text} 
}

func (e *errorString) Error() string { 
    return e.text 
}

The other can generate error The method of type value is to call fmt In bag Errorf function :

package fmt
import "errors"

func Errorf(format string, args ...interface{}) error {
    return errors.New(Sprintf(format, args...))
}

2,error Use of interfaces .

1, A simple example .

package main

import "fmt"
import "errors"

func main() {
	// First use fmt Bad method in package 
	//var err1 error = fmt.Errorf("s%","this is normal err1")  Equivalent to the following 
	err1 := fmt.Errorf("%s", "this is normal err1")
	fmt.Println("err1 = ", err1)

	// Or use it directly error package 
	err2 := errors.New("this is normal err2")
	fmt.Println("err2 = ", err2)

}

2, How to apply .

package main

import "fmt"
import "errors"

func MyDiv(a, b int) (result int, err error) {
	err = nil
	if b == 0 {
		err = errors.New(" The denominator cannot be 0")
	} else {
		result = a / b
	}
	return
}

func main() {
	result, err := MyDiv(10, 0)
	if err != nil {
		fmt.Println("err = ", err)
	} else {
		fmt.Println("result = ", result)
	}

}
原网站

版权声明
本文为[Erya preaches Buddhism]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206121731439445.html