Go Methods and Interfaces
【Go Methods and Interfaces】
1、Go does not have classes. However, you can define methods on struct types.
The method receiver appears in its own argument list between the func
keyword and the method name.
2、You can declare a method on any type that is declared in your package, not just struct types.
However, you cannot define a method on a type from another package (including built in types).
3、Methods can be associated with a named type or a pointer to a named type.指针接收器与变量接口器是不一样的。变量接收器会有拷贝,而指针接收器没有拷贝。
4、interface由一系列方法组成。
A value of interface type can hold any value that implements those methods.
5、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.
6、类型通过实现那些方法来实现接口。 没有显式声明的必要;所以也就没有关键字“implements“。
隐式接口解藕了实现接口的包和定义接口的包:互不依赖。
因此,也就无需在每一个实现上增加新的接口名称,这样同时也鼓励了明确的接口定义。
7、error也是一内置接口。As with fmt.Stringer
, the fmt
package looks for the error
interface when printing values.
8、Functions often return an error
value, and calling code should handle errors by testing whether the error equals nil
.
9、Read接口。
10、Package http serves HTTP requests using any value that implements http.Handler
:
11、Package image defines the Image
interface:
参考:https://tour.golang.org/methods/8
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。