liveBook · Manning

Pure function

As explained in Write Powerful Rust Macros

A pure function is a function with no observable side effects whose result depends only on its input parameters.

A pure function has no observable side effects, and its return value depends only on its input parameters. The same inputs therefore produce the same result, making the function easier to understand and use. section 7.2 section 7.12

fn sum_if_big_enough(a: i32, b: i32) -> i32 {
    if a > 100 && b > 1000 {
        a + b
    } else {
        0
    }
}

This Rust example computes its result entirely from its parameters, without consulting external resources. section 7.2

Contrasting external state

A function that sums two numbers when they pass fixed thresholds remains pure. Replacing those checks with a database query makes it impure: the database can change, fail, or return a different answer for the same arguments. section 7.2

Use purity to simplify implementation and testing:

  • Move transformations and business logic into pure functions where possible. section 6.5
  • Keep impure code that communicates with databases or other outside parties small. section 6.5 section 7.2
  • Test pure functions directly, reducing dependence on mocks or real external dependencies. section 6.5

How Write Powerful Rust Macros covers it

How deep it goes
Defines determinism and side effects, contrasts database access, and applies the distinction to testing and code organization.
Examples
Demonstrates fixed-threshold summation and contrasts it with summation governed by a database query.
What you can do after
Apply pure functions to write deterministic business logic that can be tested without mocking external dependencies.
How it connects
Connects pure functions with impure functions, side effects, referential transparency, and memoization.

Also explained in

Compare how 19 books explain pure function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Write Powerful Rust Macros. The section links point to the parts of the book it draws on.