liveBook · Manning

Impure function

As explained in Write Powerful Rust Macros

An impure function is a function whose behavior or result can depend on or produce effects beyond its input parameters.

An impure function depends on or produces effects beyond its input parameters. Its output can change when an external resource changes or fails. section 7.2

Database queries make a function impure because the same arguments can produce different results after database changes or failures. Calling an impure helper also makes its caller impure: the external dependency’s effects spread outward. section 7.2

Common effects include:

  • Reading or modifying a database or communicating with another system. section 7.2
  • Logging, which is usually a relatively safe side effect but can still fail because of operating-system problems. section 7.2
  • Breaking ordinary control flow through panics or exception-like behavior; Result provides a more idiomatic error-handling alternative in Rust. section 7.0 section 7.12

Database-dependent summation

A function that sums two numbers only when a database-backed predicate approves them is impure. The predicate’s result may change between calls, even when both arguments remain unchanged. section 7.2

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

Inspect the Rust example where an external database check replaces a deterministic condition and makes the surrounding function impure. section 7.2

How Write Powerful Rust Macros covers it

How deep it goes
Explains external dependence, nondeterminism, transitive impurity, side effects, logging, and testing implications without formal implementation detail.
Examples
Uses deterministic summation, database-dependent summation, logging, macro tests, and panics versus Result as teaching examples.
What it assumes
Assumes familiarity with Rust functions, parameters, return values, databases, and basic unit testing.
What you can do after
Evaluate function boundaries, isolate transformations in pure functions, and test impure edges with focused integration coverage.
How it connects
Connects impure functions to pure functions, side effects, databases, error handling, panics, Result, and integration testing.

Also explained in

Compare how 2 books explain impure 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.