0

Rust – How to Create Struct Methods

Structs can have methods but, unlike fields, are not defined within their structure. The methods need to be “implemented” after a Struct definition using the impl keyword.

A Calculator Struct

Let us say we have a Struct  called Calculator  that does basic arithmetic – add, subtract, multiply, and divide. Note that all codes are within the main.rs  file.

Struct Methods

A Struct method can either be a static or instance method. A static method does not require an instance of the Struct to get invoked; however, a instance method does require an instance.

Static Methods

Static methods are created as follow. We do not declare &self  as the first parameter of the function.

To invoke the static methods, we use the ::  (double-colon operator) between the Struct  and the static function.

Output

Instance Methods

Instance methods are created as follow. We declare &self  as the first parameter of the function.

To invoke the instance methods, we first create an instance of the Struct  and use the .  (dot operator) between the instance and the function.

Output

Karl San Gabriel

Karl San Gabriel

Professional Software Developer