Method call syntax
Rust is not an object oriented programming language because it does not support inheritcance, which is a bad practice because the saying goes like "Prefer Composition over inheritance".
If you are familiar with OOP languages you would've benefitted mightily from the method call syntax as IDE's can implement auto-completion for fields and methods.
So in Rust we get the benefits of method call syntax without the cons of spaghetti code which is the eventual result of preferring inheritance.
Also inheritance affects performance and memory usage negatively.
How to achieve method call syntax in rust?
Let's review the bitcoin
crate to understand this.
using method call syntax
The pub
keyword suggests that the entity following can be used from anywhere, similar to public
in Java or C#.
There are associated constants like ZERO
, ONE_SAT
etc.,
Why u64 is chosen?
Let's review why u64
is chosen but not u32
or u128
etc., The limit on the number of bitcoins in circulation is 21_000_000
which is 21_000_000 * 100_000_000
satoshis. One can quickly verify using python interpreter that 2^50 < 21_000_000 * 100_000_000 < 2^51
. Which means we need at least 51 bits to store all possible satoshi values, hence 64 bit unsigned integer is used.
Encapsulation
You might wonder what is the purpose of this Amount
type, it is just a wrapper over u64
right? Because this is how we achieve encapsulation in Rust. A library should make sure that the types defined are used as intended. u64
will behave like an unsigned integer, but satoshis should have the behaviours as defined in the bitcoin network and ecosystem.
The method call syntax ensures that the user gets to know everything on how to use the Amount
type just by examining the function syntax and documentation, dig deeper into the code if necessary.
Last updated