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.

  Go Methods and Interfaces

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).

  Go Methods and Interfaces

3、Methods can be associated with a named type or a pointer to a named type.指针接收器与变量接口器是不一样的。变量接收器会有拷贝,而指针接收器没有拷贝。

  Go Methods and Interfaces

4、interface由一系列方法组成。

  A value of interface type can hold any value that implements those methods.

  Go Methods and Interfaces

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.

  Go Methods and Interfaces  Go Methods and Interfaces

6、类型通过实现那些方法来实现接口。 没有显式声明的必要;所以也就没有关键字“implements“。

  隐式接口解藕了实现接口的包和定义接口的包:互不依赖

  因此,也就无需在每一个实现上增加新的接口名称,这样同时也鼓励了明确的接口定义。

7、error也是一内置接口。As with fmt.Stringer, the fmt package looks for the error interface when printing values.

  Go Methods and Interfaces

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

  Go Methods and Interfaces

9、Read接口。

  Go Methods and Interfaces

  Go Methods and Interfaces

10、Package http serves HTTP requests using any value that implements http.Handler:

  Go Methods and Interfaces  Go Methods and Interfaces

11、Package image defines the Image interface:

  Go Methods and Interfaces  Go Methods and Interfaces

参考:https://tour.golang.org/methods/8  

 

相关文章: