Methods and Interfaces

methods and intefaces in golang

Methods

a method is just a function with a receiver argument.

type Vertex struct {
  X, Y float64
}

// Declaring Method with a truct type
func (v Vertex) Abs() float64 {
  return math.Sqrt(v.X * v.X + v.Y * v.Y)
}

v := Vertex{1, 2}
v.Abs() // Calling a Method
----------------------------------

// You can declare a method on non-struct types, too.
func (f MyFloat) Abs() float64 {
	if f < 0 {
		return float64(-f)
	}
	return float64(f)
}
------------------------------

// Mutation with Pointer receivers
// Scale scales the Vertex by a given factor. This method has a pointer receiver (*Vertex).
func (v *Vertex) Scale(f float64) {
	v.X = v.X * f
	v.Y = v.Y * f
}

v := Vertex{3, 4} // Initial Vertex: {X:3 Y:4}
v.Scale(10) // Vertex after scaling: {X:30 Y:40}
v.Abs() // Absolute value after scaling: 50
------------------

p := &v
p.Abs() // the method call p.Abs() is interpreted as (*p).Abs() 

Interfaces

An interface type is defined as a set of method signatures.

Type Assertions:

Type Switches:

Stringers:

Errors

Readers

Last updated

Was this helpful?