A method is a function that is defined as a member of a type (primitive, composite, or class). Methods are typically invoked through a type with the dot operator or the arrow operator (in C++, for object pointers), i.e., type.method().

It is mainly seen in the context of object-oriented programming, where methods are member functions of classes. Many non-OOP languages also allow methods, broadly as type-specific member functions.

Methods usually also allow the modification of the underlying type itself. This is doable via special keywords, like this (in C++) or self (in Java, Rust). They serve as a constant pointer to the type/object itself.

Note that only methods can access private members of the class. Functions outside of the class can’t! But to bypass this restriction we can set some functions as friend functions, where it can access private members and the LHS can be of a type that’s not the class. But they’re not members of the class and must be implemented outside. On a class level, methods of the same class are able to access each other’s private attributes.

For a multi-line method call, we go from left to right. This isn’t true for overloaded operators.

Common types and concepts

Language-specific

In Rust

We add methods to structs with:

impl Class {
	fn method(&self) -> u32 {
		// etc
	}
}

Associated functions don’t have self as the first parameter (and thus aren’t methods). They’re not accessed via the dot notation, but instead the scope resolution operator ::. They’re mainly used as constructors to return -> Self. These are similar to static methods in C++.

In Go

Go’s methods are similar to Rust in that they’re implemented on types. A method is denoted by a type in between the func keyword and the method name.

type Vertex struct {
	X, Y float64
}
 
func (v Vertex) Abs() float64 {
	// and so on
}