Rust, Software Development

Static and Instance Methods in Struct in Rust

A struct can have its own static and instance methods (or functions) but are not created within the struct itself. These methods exist in a separate block using impl and they can be either static or instance methods.

How to Create Methods

Consider a struct called Calculator that performs arithmetic through its methods – static or instance.  Initially, the struct would be pub struct Calculator {} – without any methods. If we need to add methods to Calculator, we would use impl as follows.

Impl can also be used to implement traits.

Define Instance Methods

Instance methods exist in the context of a struct instance. Therefore, the codes must first create an instance of a struct to access its methods. For instance methods, we need to refer to its instance using the first parameter. By convention, it’s called &self.

The following code snippet runs these methods. It uses a struct expression to create an instance of the struct. Then, it assigns the instance to cal. Finally, it runs the methods using cal.

Define Static Methods

Static methods do not need struct instances and do not have &self as their first parameter. Consider the following codes.

To run these static methods, we need to use the ::  (double-colon operator) between struct name and function. We use Calculator to run add and other methods.

Run Like The Other – Static or Instance Method

We cannot use instance methods like static methods. Consider the following code snippets.

This will not work because the method expects the first argument for the &self parameter.

The same thing goes for static methods.

The codes will fail – error[E0599]: no method named add found for type Calculator in the current scope.

You Might Also Like