Pure functions are the second technique that we recommend to prevent hard-to-reproduce bugs. Pure functions can be thought of as an extension of the avoid side-effects principle. The definition of a pure function is a function where the following is true:
- No changes are caused outside of the function (no side-effects)
- The return value does not depend on anything but the function parameters
Here are some examples of pure functions:
fn p0() {}
fn p1() -> u64 {
444
}
fn p2(x: u64) -> u64 {
x * 444
}
fn p3(x: u64, y: u64) -> u64 {
x * 444 + y
}
fn main()
{
p0();
p1();
p2(3);
p3(3,4);
}
Here are some examples of impure functions:
use std::cell::Cell;
static mut blah: u64 = 3;
fn ip0() {
unsafe {
blah = 444;
}
}
fn ip1(c: &Cell<u64>) {
c.set(333);
}
fn main()
{
ip0();
let r = Cell::new(3);
ip1(&r);
ip1(&r);
}
Rust does...