- GO does not have class. However, we can define methods on types.
- A method is a function with a special receiver argument.
- The receiver appears in its own argument list between the
func
keyword and the method name.
func (v Vertex) Abs() float64 {
return math.Sqrt(v.Xv.X + v.Yv.Y)
} -
Remember: A method is just a function with a receiver argument. This one functions the same as the previous one.
func Abs(v Vertex) float64 {
return math.Sqrt(v.Xv.X + v.Yv.Y)
} -
Important: You can only declare a method with a receiver whose type is defined in the same package. That includes the built-in type. However you can use
type MyFloat float64 - Pointer receivers:
func (v *Vertex) Scale(f float64) {
v.X = v.X * f
v.Y = v.Y * f
}Method with pointer receivers can modify the value to which the receiver points. ( GO is passing by value by default)
Method and pointer indirection. Method will be called automatically even v is a value not a pointer, but function will not.
var v Vertex
/* Method /
v.Scale(5) // OK
p := &v
p.Scale(10) // OK
/ function */
ScaleFunc(v) // Compile error!
ScaleFunc(&v) // OKThe equivalent thing happens int the reverse direction. The method takes value as receiver can also takes pointer while function cannot.
Using pointer as receiver is encouraged. In general, all methods on a give type should have either value or pointer receivers, but not a mixture of both.
- Interfaces
- An interface type is defined by a set of methods.
type Abser interface {
Abs() float64
} - A type implements an interface by implementing the methods.
-
Stringer
. AStringer
is a type that can describe itself as a string. Thefmt
pkg look for this interface to print values.
type Stringer interface {
String() string
}
- Error
- The error type is a built-in interface similar to
fmt.Stringer
.
type error interface{
Error() string
}
- Readers
- The IO package specifies the
io.Reader
interface, which denote the read end of a stream of data.
- HTTP servers
*Packagehttp
serves HTTP request using any value that implementshttp.Handler:
- Image
- Package image defines the
Image
interface.