This is a creation in Article, where the information may have evolved or changed.
The essential type of the Go language---the native code in Error,go is small and easy to master.
What's error ?
The official explanation, error is a built-in interface, defined as follows:
// The error build-in interface type is the conventional// interface for representing an error condition, with// the nil value representing no error.type error interface { Error() string}
After understanding the error type, we can easily interpret errors the source code under the catalogue.
Reading of the errors.go errors package
Look at the source bar, really very little.
// New returns an error that formats as the given text.func New(text string) error { return &errorString{text}}// errorString is a trivial implementation of error.type errorString struct { s string}func (e *errorString) Error() string { return e.s}
Here comes a point of knowledge, is the interface understanding, if you understand this, 任意数据类型实现了接口中的所有方法, 那么这个数据类型就实现了该接口. it is accessible to understand the above code.
The interface usage scenarios I encountered
I feel interface is an all-round player, use a lot of scope, if you want to know more comprehensive understanding interface , please search it yourself, here summarize the use of the scene I encountered interface :
- Interface interface
- Interface Values & Parameters
Interface interface
Go is intetface different from other languages (Java, C # ...), just to implement all the methods within its interface, is to implement the interface, not like Java implements InterfaceName . As errors in the chestnut:
// 接口: error// errorString 实现了 Error()方法, 即实现了 error 接口
Interface Values & Parameters
interfaceWhat value can be stored? The answer is: What value can be saved, omnipotent. It's like an Object in Java. It is so widely used in reflection. Three practical scenarios were said:
- To design a linked list, the type of the value on each node is arbitrary, and the data type of the value is
interface declared:val interface
- Design a method that has a parameter of any type then the parameter type is used
interface to declare:param interface{}
- Design a method where the parameter type is arbitrary and the number of arguments is arbitrary, which is also used
interface to declare:params ...interface{}
The above is the summary after learning, if there are errors, please treatise.
Great articles, continuous updates, please pay attention to the public number:
Handsome beauty sweep