When to use a field or a method in Rust structs?

Solution 1:

TLDR; it depends on the use case.

IMHO

This starts to become opinionated very fast. Generally speaking your answer will be driven by use-cases.

On modern systems, experience says that it's better to keep dependent params as functions and only optimize the caching of results as a special case.

Example 1:

Length and height remain constant over life of the Rectangle; pre-calculating may be useful. (Consider having to do it for 10^6 rectangles e.g.)

Example 2:

Your height and length get modified ... then do you precalculate? Do you cache the result?

Example 3:

You are constantly updating the third param based on the user updating any of the other two :-)

@prog-fh made a comment about accessing memory is expensive. I would say that you have to consider that both ways. Fetching two values into the CPU and calculating it can be potentially more expensive than accessing exactly one pre-calculated value.

so IMHO, and in line with what every one says,

It depends :-)