A practical tutorial in types, logic, comparisons, repetitions, ownership, and integration
Dimitris Kokoutsidis — 4 December 2026
This tutorial assumes that you understand FileMaker calculations, scripts, records, repeating fields, JSON parameters, and client/server execution. It does not assume previous experience with C, C++, or memory management.
The goal is to make you able to read Rust, write small components, and connect them to a FileMaker solution. We begin with familiar business logic and build toward an independently testable quote calculator with command-line and local HTTP interfaces.
Scope. This is a comprehensive foundation, not a catalog of every standard-library method. It covers the main language structures and the advanced constructs you will encounter while reading real Rust. FileMaker script listings are human-readable instructions for recreating steps in Script Workspace; they are not clipboard XML, but guaranteed importable .fmscript syntax. Rust examples marked “intentionally rejected” demonstrate compiler errors. Other short examples are independent snippets unless stated otherwise. The companion project is the executable reference.
Sources and versions. Technical references are linked beside the relevant material and collected at the end. The project uses Rust edition 2024. An edition selects language compatibility rules; it is not the compiler’s release year. The exact compiler, dependency resolution, and completed checks appear in the companion project’s VALIDATION.md. Examples use the supported Axum 0.8 API rather than assuming that any future major release will work unchanged.
Contents
- The change in mental model
- Installing Rust and understanding Cargo
- Reading Rust syntax
- Variables, scope, constants, and mutability
- Types and FileMaker data conversion
- Operators, comparisons, and Boolean logic
- Conditional logic and pattern matching
- Repeated execution: loops and recursion
- Repeating fields, repeating variables, arrays, and vectors
- Text, Unicode, and FileMaker value lists
- Functions and explicit context
- Ownership, borrowing, and lifetimes
- Structs, methods, enums, and business states
- Collections, finding, sorting, and grouping
- Errors, optional values, and validation
- Generics, traits, closures, and programming styles
- Modules, crates, dependencies, and documentation
- Advanced structures: smart pointers, async, macros, and unsafe
- A complete quote-calculation project
- Calling Rust from FileMaker
- Persistence, transactions, security, and deployment
- Testing and debugging
- Common translation mistakes
- Exercises with worked answers
- Reference tables and further reading
1. The change in mental model
1.1 FileMaker is a platform; Rust is a language and toolchain
A FileMaker file brings together schema, records, relationships, layouts, calculations, scripts, accounts, and application behavior. A Rust program starts with code and explicitly selected libraries. It does not automatically contain a database, a current record, a relationship graph, or a layout engine.
Consequently, a Rust struct Customer is not a FileMaker table. It defines the shape of one in-memory value. A Vec<Customer> holds a sequence of values. Neither persists them after the process ends unless you write persistence code.
This distinction determines sensible architecture. Keep a working FileMaker application responsible for the business interface and database. Add a Rust component where you have a clear processing boundary: validate a document, calculate totals, parse a format, transform a large payload, or provide a service.
1.2 Context becomes input
Consider a FileMaker calculation:
Quotes::Quantity * Quotes::UnitPrice
It depends on evaluation context. The same field reference may produce different results when evaluated from another record or table occurrence.
The corresponding Rust function receives values:
fn line_total(quantity: u32, unit_cents: u64) -> Option<u64> {
u64::from(quantity).checked_mul(unit_cents)
}
The function knows nothing about layouts or records. Some(total) means the multiplication succeeded within the numeric range; None means it overflowed. We will unpack this syntax later.
The practical benefit is reproducibility: given the same inputs, this function returns the same result. A test does not need to navigate to a layout or establish a found set.
1.3 A translation map, with limits
| FileMaker concept | Rust concept | Where the analogy stops |
|---|---|---|
| Calculation variable | Local binding with let | Rust has lexical scope and static types |
$variable | Local binding or function parameter | A nested function does not inherit caller locals |
$$variable | Explicit application or session state | No automatic FileMaker-style session global |
| Custom function | Function with fn | Parameters and return type form a compile-time contract |
| Script parameter JSON | Typed input structure | Parsing can reject missing or incorrectly typed fields |
| Script result | Function return value | May be a struct, enum, Option, or Result |
| Record fields | Fields in a struct value | Changing the struct does not save a record |
| Found set | A selected collection or query result | No implicit record cursor or database membership |
| Repeating field | Array, vector, or keyed map | Indexing, empty slots, and storage semantics differ |
| Value list of allowed states | Enum | An enum is a type, not a UI value-list definition |
Get(LastError) | A returned Result | Error belongs to the operation, not a global last-error slot |
Perform Script On Server | A remote service call, loosely | Spawning a Rust thread does not create an FMSE session |
These are learning bridges. Avoid treating them as one-for-one implementation rules.
2. Installing Rust and understanding Cargo
2.1 Install the toolchain
Use the official Rust installation instructions. rustup manages toolchains and normally installs both the compiler, rustc, and the build tool, cargo.
On Windows, use the official installer and follow its instructions for the required C++ build tools. A Windows Rust executable and a Linux executable built inside WSL target different operating systems. Choose the environment in which the component must actually run.
On macOS, ensure that the required developer command-line tools are available. On Linux, ensure that a native linker and the platform build prerequisites are installed. Installation details vary by operating system; do not copy instructions for another platform without checking them.
Verify:
rustc --version
cargo --version
rustup show
2.2 Create your first project
cargo new hello_filemaker --edition 2024
cd hello_filemaker
cargo run
Cargo creates Cargo.toml and src/main.rs. Replace src/main.rs with:
fn main() {
let developer = "Dimitris";
println!("Hello, {developer}, from Rust.");
}main is this program’s entry point. println! prints a formatted line; the exclamation mark identifies a macro invocation. Cargo compiles the program before running it.
2.3 The commands you actually need
| Command | Purpose |
|---|---|
cargo check | Check code without producing a final executable |
cargo run | Build and run the development executable |
cargo test | Run automated tests |
cargo fmt | Apply the standard formatter |
cargo clippy | Run additional lint checks |
cargo build --release | Produce an optimized build |
cargo doc --open | Generate and open project API documentation |
rustc --explain E0382 | Explain a compiler diagnostic |
Install missing formatter/linter components with rustup component add rustfmt clippy. A release executable is normally placed under target/release; Windows adds .exe to executable filenames. Debug builds prioritize development; use release builds for performance measurements. See Cargo’s introduction.
2.4 Manifest versus lockfile
Cargo.toml describes your package and acceptable dependency versions. Cargo.lock records the exact resolved dependency graph. A declaration such as serde = "1" is a compatible version requirement, not a permanent pin to whatever version you first installed.
For the application in this tutorial, commit the generated lockfile. cargo build --locked requires the existing resolution instead of silently changing it. A lockfile alone does not freeze the compiler, operating system, linker, or build environment. See Cargo.toml versus Cargo.lock.
3. Reading Rust syntax
Before memorizing individual constructs, learn to read this function:
fn label(id: &str, count: usize) -> String {
format!("{id}: {count} lines")
}
| Syntax | Meaning here |
|---|---|
fn | Define a function |
label | Function name |
id: &str | Parameter named id, borrowing UTF-8 text |
count: usize | Parameter named count, an unsigned index-sized integer |
-> String | Return an owned string |
{ ... } | Function body or another block |
format! | Construct formatted text |
Final expression without ; | Return the block’s value |
Many Rust constructs are expressions: they produce values. This makes them feel familiar to a FileMaker developer who composes calculations.
let message = {
let count = 3;
format!("{count} records")
};
The block produces a String. Its inner count is unavailable afterward. A semicolon after the final format! would discard that value and make the block produce (), the unit value.
Rust normally uses snake_case for variables, functions, and modules; PascalCase for types and traits; and SCREAMING_SNAKE_CASE for constants. // starts a line comment. /* ... */ is a block comment. /// documents the following item. Read more in Functions.
4. Variables, scope, constants, and mutability
4.1 let introduces a binding
FileMaker:
Set Variable [ $quantity ; Value: 2 ]
Set Variable [ $quantity ; Value: $quantity + 1 ]
Rust:
let mut quantity: u32 = 2;
quantity += 1;
Without mut, reassignment is rejected. This makes change visible in the declaration.
4.2 Shadowing is a new binding
let quantity = "12";
let quantity: u32 = quantity.parse().expect("Teaching example: valid integer");
The second let creates a new binding with the same name and a different type. It does not mutate a string into a number. The expect call panics if parsing fails; later chapters replace it with ordinary error handling for external input.
4.3 Lexical scope
let customer_id = "C-100";
{
let note = "internal";
println!("{customer_id}: {note}");
}
// `note` is out of scope here.
A Rust local is not a $ variable shared across a script’s calculations. A separately declared function receives only its explicit parameters and accesses other names allowed by the language’s scope rules. Closures can capture local values; we cover those separately.
4.4 const, static, and session state
const MAX_LINES: usize = 1_000;
A constant requires a type and a constant-evaluable initializer. A static has a fixed storage location for the program’s lifetime. Neither automatically represents a FileMaker user’s session.
For per-user state, prefer a struct such as SessionContext { account_id, locale } and pass it to the code that needs it. Shared mutable process state requires explicit synchronization or another suitable design. Read Variables and Mutability.
5. Types and FileMaker data conversion
5.1 Primitive and compound types
| Rust type | Meaning | Typical FileMaker-facing use |
|---|---|---|
bool | true or false | A validated checkbox or Boolean JSON property |
u8, u16, u32, u64, u128 | Unsigned integers | Counts, byte values, nonnegative quantities |
i8, i16, i32, i64, i128 | Signed integers | Deltas, balances, signed counters |
usize, isize | Pointer-width integers | Collection lengths and indexes |
f32, f64 | Binary floating point | Measurements, approximations, scientific calculations |
char | One Unicode scalar value | A parsed scalar, not necessarily a visible character |
&str | Borrowed UTF-8 text | Read-only function input |
String | Owned, growable UTF-8 text | Stored names, IDs, generated text |
[T; N] | Fixed-length array | A fixed set of repetition slots |
Vec<T> | Growable ordered sequence | Request lines or selected records |
&[T] | Borrowed slice | Read a sequence without owning it |
(A, B) | Tuple | A small group of differently typed values |
() | Unit value | Successful operation with no useful payload |
These types differ in permitted values and operations. u32 can hold 0 through 4,294,967,295. Negative input cannot be represented in it. A usize width follows the target platform; do not use it as an externally specified 64-bit identifier type. See Data Types.
5.2 FileMaker’s field categories do not select one universal Rust type
| FileMaker data | Boundary representation | Rust choice after validation |
|---|---|---|
| Text | JSON string | String |
| Number holding a quantity | JSON integer | u32, or a decimal type for fractional quantities |
| Number holding an amount | Integer minor units or decimal string | Checked integer or a selected decimal implementation |
| Date | Explicit YYYY-MM-DD text | A chosen date library’s validated date type |
| Time of day | Explicit text with defined precision | A selected time type |
| Timestamp | Documented format with offset/time-zone policy | A suitable date-time type |
| Container | Bytes, upload, or an authorized resource reference | Vec<u8>, streaming body, or path/reference type |
| Empty optional field | Explicit JSON null or a documented omission | Option<T> |
Rust’s standard library has durations and system/monotonic clocks, but not a full business-calendar date/time model. Select and verify a date/time library when the application needs one. Do not silently interpret a FileMaker timestamp as UTC: first establish what the stored value means.
5.3 Conversions are explicit
let quantity: u32 = 12;
let wide_quantity: u64 = u64::from(quantity);
let parsed: Result<u32, _> = "12".parse();
let narrow: Result<u8, _> = u8::try_from(300_u32);
assert!(narrow.is_err());
from is for supported infallible conversions. try_from can fail. The as operator performs casts whose behavior depends on the source and destination types; it is not validation. For example, narrowing an integer can discard bits. Use checked conversions at business boundaries.
Avoid converting a monetary JSON string through f64 merely to make it an integer. That introduces rounding before your accounting rule even starts.
5.4 Money needs a contract
Our project stores whole euro cents in u64: €12.50 becomes 1250. Quantities are whole numbers. Percentage rates are basis points: 10% becomes 1000, 24% becomes 2400, and 100% becomes 10000.
This model is an example, not a claim that every currency has two decimal places. It does not handle fractional manufacturing quantities or prices below one cent. For those cases, define a finer scale or a decimal representation and the conversion/rounding policy.
Use checked_add, checked_mul, and related methods so overflow becomes a handled outcome. Ordinary integer overflow behavior depends on build settings; a business rule must not depend on debug/release differences. See the integer checked arithmetic API.
6. Operators, comparisons, and Boolean logic
6.1 Operator translation
| Intention | FileMaker | Rust |
|---|---|---|
| Equality test | a = b | a == b |
| Inequality | a ≠ b or a <> b | a != b |
| Assignment | Set Variable or Set Field | a = b |
| Less/greater | <, ≤, >, ≥ | <, <=, >, >= |
| Logical AND | and | && |
| Logical OR | or | ` |
| Logical NOT | not | ! |
| Boolean XOR | xor | ^ on bool values |
| Addition/subtraction | +, - | +, - |
| Multiplication/division | *, / | *, / |
| Remainder | Mod in some numerical cases | %, with sign semantics to check |
| Text concatenation | & | Often format!, push_str, or + |
In Rust, & is frequently a borrow operator. On supported values it can also mean bitwise AND. It does not concatenate text. && and || short-circuit; & and | on Boolean values evaluate both operands. See Operator Expressions.
6.2 Conditions must be Boolean
let quantity = 3_u32;
if quantity > 0 {
println!("Has quantity");
}
if quantity { ... } is rejected. Unlike FileMaker calculations that use numeric truth values, Rust does not implicitly treat any nonzero integer as true.
a | b | a && b | a || b | a ^ b |
|---|---|---|---|---|
| false | false | false | false | false |
| false | true | false | true | true |
| true | false | false | true | true |
| true | true | true | true | false |
!true is false and !false is true. When combining comparisons, write parentheses to expose business grouping rather than relying on a reader to remember every precedence rule:
let is_approved = true;
let has_stock = false;
let allow_backorder = true;
let may_fulfill = is_approved && (has_stock || allow_backorder);
assert!(may_fulfill);
Short-circuiting makes a guard useful: index < values.len() && values[index] > 0 does not evaluate the indexed expression when the first test is false. For user-supplied indexes, .get() often expresses the intent more directly.
6.3 Integer division and signed remainder
assert_eq!(5 / 2, 2);
assert_eq!(5.0 / 2.0, 2.5);
assert_eq!(-5 % 3, -2);
assert_eq!((-5_i32).rem_euclid(3), 1);
Do not translate Mod blindly when negative values are possible. Decide whether you need a signed remainder or a nonnegative Euclidean remainder. Parenthesize negative literals before method calls when necessary to make the intended receiver explicit.
6.4 Text comparison is not FileMaker collation
assert!("A" != "a");
assert!("FileMaker".eq_ignore_ascii_case("filemaker"));
Ordinary Rust string equality compares the encoded text exactly. Ordering is lexicographic, not a locale-aware dictionary sort. eq_ignore_ascii_case is deliberately limited to ASCII. It is not a Greek, Japanese, or universal Unicode collation function.
When matching human names, specify case folding, Unicode normalization, and locale rules. When matching an application identifier, exact comparison may be the correct contract. Do not apply a human-name comparison rule to security tokens.
6.5 Floating-point comparison
f64 calculations may have rounding error, and NaN does not behave like an ordinary number in comparisons. Define tolerances appropriate to the measurement when testing approximate results. For an integer-cent invoice total, compare integer cents exactly. Avoid adding an arbitrary epsilon to hide a poorly defined accounting representation.
7. Conditional logic and pattern matching
7.1 if and else
FileMaker:
If ( $quantity > 0 ; "Ready" ; "Empty" )
Rust:
let quantity = 3;
let label = if quantity > 0 { "Ready" } else { "Empty" };
Both branches must produce compatible types. You cannot return text in one branch and an integer in the other without explicitly representing that choice.
7.2 Case and match
For ordered predicate checks, use an if / else if chain:
let score = 85;
let grade = if score >= 90 {
"A"
} else if score >= 80 {
"B"
} else {
"C"
};
For alternatives in one value, use match:
let status = "approved";
let label = match status {
"draft" => "Editable",
"approved" => "Locked",
"sent" | "accepted" => "Customer-facing",
_ => "Unknown",
};
The wildcard _ handles remaining cases. With an enum, listing all variants can make a later new variant trigger a useful compiler error. match does not fall through from one matching arm to the next. See The match Construct.
7.3 Optional values: if let and let else
let email: Option<&str> = Some("[email protected]");
if let Some(address) = email {
println!("Send to {address}");
}
Use let else to exit early when a required pattern is absent:
fn email_label(email: Option<&str>) -> String {
let Some(address) = email else {
return "No email supplied".to_owned();
};
format!("Send to {address}")
}
The else block must leave that flow, for example by returning. This keeps the successful path less deeply nested. See Concise Control Flow.
7.4 Destructuring and guards
let payment = (true, 5_000_u64);
let label = match payment {
(true, amount) if amount >= 5_000 => "Large paid order",
(true, _) => "Paid order",
(false, _) => "Unpaid order",
};
The pattern separates the tuple’s components; the if is a match guard. Patterns also extract struct fields and enum payloads. Some(value) in a pattern binds the contained value; it is not a function call. See Pattern Syntax.
8. Repeated execution: loops and recursion
8.1 A direct Loop / Exit Loop If translation
FileMaker:
Set Variable [ $i ; Value: 1 ]
Loop
Exit Loop If [ $i > 3 ]
# Process repetition $i
Set Variable [ $i ; Value: $i + 1 ]
End Loop
Rust:
let mut i = 1;
loop {
if i > 3 {
break;
}
println!("Repetition {i}");
i += 1;
}
This preserves the order of the checks. Moving the exit condition below the work changes whether the body runs at least once.
8.2 Prefer for for a known sequence
for repetition in 1..=3 {
println!("Repetition {repetition}");
}
1..=3 includes 3. 1..3 excludes it. 0..values.len() produces the valid index range for a collection, but direct iteration is usually easier to read:
let amounts = [100_u64, 250, 400];
for amount in &amounts {
println!("{amount}");
}
8.3 while
FileMaker’s While calculation and Rust’s while both repeat while a condition remains true, but their surrounding expression forms differ. Claris documents the FileMaker evaluation order here.
FileMaker:
While (
[ i = 1 ; total = 0 ] ;
i <= 3 ;
[ total = total + i ; i = i + 1 ] ;
total
)
Rust:
let mut i = 1;
let mut total = 0;
while i <= 3 {
total += i;
i += 1;
}
assert_eq!(total, 6);
A Rust while expression yields (), so you read total after it. Another solution is (1..=3).sum::<i32>(). See Rust Control Flow.
8.4 break, continue, and a value from loop
let mut attempts = 0;
let outcome = loop {
attempts += 1;
if attempts == 2 {
continue;
}
if attempts == 3 {
break "finished";
}
};
assert_eq!(outcome, "finished");
continue starts the next iteration. break exits. A plain loop can return a value through break value; ordinary for and while loops do not support that same value-returning break form.
For nested loops, a label such as 'search: for ... lets break 'search leave the named loop. Labels are not arbitrary goto destinations.
while let combines repetition with matching:
let mut pending = vec!["Q-1", "Q-2"];
while let Some(id) = pending.pop() {
println!("Process {id}");
}
This consumes from the end: Q-2 is processed before Q-1. For a first-in-first-out work queue, choose VecDeque and pop_front() instead of assuming this is a found-set traversal.
8.5 Recursion
fn sum_down(n: u32) -> u64 {
if n == 0 {
0
} else {
u64::from(n) + sum_down(n - 1)
}
}
Use this only for small teaching inputs. Rust does not guarantee tail-call optimization, and deep recursion can exhaust the stack. A loop is the practical choice for processing a large collection. FileMaker’s SetRecursion is not a configuration switch for a Rust process.
9. Repeating fields, repeating variables, arrays, and vectors
9.1 Three different ideas must stay separate
- A repeating field is schema-defined data with numbered repetitions.
- A repeating variable is a variable addressed with a repetition index.
- A loop repeats execution.
Rust has separate facilities for storage and iteration. Choosing an array does not execute a loop, and writing a loop does not imply a repeating field.
9.2 One-based versus zero-based indexing
FileMaker’s GetRepetition and bracket notation access a numbered field repetition. Rust arrays and vectors begin at index zero.
| Position | FileMaker field | Rust array/vector |
|---|---|---|
| First | Amount[1] | amounts[0] |
| Second | Amount[2] | amounts[1] |
| Tenth | Amount[10] | amounts[9] |
Convert at the boundary, with checks:
fn fm_repetition<T>(values: &[T], repetition: usize) -> Option<&T> {
let index = repetition.checked_sub(1)?;
values.get(index)
}
let amounts = [100, 200, 300];
assert_eq!(fm_repetition(&amounts, 2), Some(&200));
assert_eq!(fm_repetition(&amounts, 0), None);
assert_eq!(fm_repetition(&amounts, 9), None);
The ? exits this Option-returning function with None if subtraction fails. It avoids subtracting one from zero.
9.3 Fixed slots: [T; N]
let mut monthly_cents: [u64; 12] = [0; 12];
monthly_cents[0] = 50_000;
monthly_cents[11] = 75_000;
The length is part of the type. [u64; 12] and [u64; 10] are different types. [0; 12] means twelve zero values, not the two-element array [0, 12].
An empty FileMaker field repetition may mean “not entered,” while zero is a valid amount. Preserve that distinction:
let mut months: [Option<u64>; 12] = [None; 12];
months[0] = Some(0); // Explicit zero.
months[2] = Some(75_000); // Entered amount.
assert_eq!(months[1], None); // Not entered.
Do not remove the absent second month and shift March into February. Positional meaning is part of the schema.
9.4 Variable length: Vec<T>
let mut lines: Vec<u64> = vec![1_250, 500];
lines.push(900);
let removed: Option<u64> = lines.pop();
assert_eq!(removed, Some(900));
A vector grows and shrinks. It holds values of one element type; that type may itself be a struct or enum. See Vectors.
Direct indexing such as lines[100] panics if the index is outside the collection. lines.get(100) returns None. Use get for indexes supplied by users or another system. A panic is not an ordinary “empty field” result.
9.5 Sparse repetition keys: use a map
If the meaning of your FileMaker repeating variable is a dictionary of keys such as 1, 200, and 9000, a vector of 9001 slots may express the wrong model. Set Variable exposes repetition as an expression; inspect the actual indexes used by the source solution.
use std::collections::HashMap;
let mut values: HashMap<i64, String> = HashMap::new();
values.insert(200, "Customer-specific setting".to_owned());
assert_eq!(values.get(&200).map(String::as_str), Some("Customer-specific setting"));
This preserves the key rather than treating it as a position. Choose the key type from the real source contract. Do not assume all repeating-variable designs are dense, bounded, or intended to mirror repeating fields.
9.6 Preserve positions during transfer
A dense array of slots can travel as:
{"monthly_cents": [50000, null, 75000, null, null, null, null, null, null, null, null, null]}
A sparse keyed structure can travel as:
{"repetitions": [{"index": 200, "value": "setting"}, {"index": 9000, "value": "other"}]}
The explicit-entry form makes key validation and duplicate detection possible. A JSON object’s keys are strings; a property named "200" is not automatically an integer key in every consumer.
9.7 Repetition-aware calculations need deliberate translation
A FileMaker repeating calculation may rely on current repetition behavior or Extend. Rust does not implicitly broadcast one scalar through an array. State the operation:
let prices = [100_u64, 200, 300];
let quantity = 2_u64;
let extended: Vec<u64> = prices.iter().map(|price| price * quantity).collect();
assert_eq!(extended, vec![200, 400, 600]);
For arbitrary money inputs, replace the simple multiplication with checked arithmetic. This snippet is deliberately small to show the mapping.
If two repeating fields represent paired data, do not zip unequal sequences without validation: zip stops at the shorter input. Prefer a vector of QuoteLine { quantity, unit_cents } so each pair stays together.
9.8 Two dimensions and borrowed subranges
let mut quarterly_slots: [[Option<u64>; 3]; 4] = [[None; 3]; 4];
quarterly_slots[0][2] = Some(12_500); // First quarter, third month.
let amounts = [100_u64, 200, 300, 400];
let middle: &[u64] = &amounts[1..3];
assert_eq!(middle, &[200, 300]);
The nested array has four fixed groups of three slots. Both indexes are zero-based. The borrowed range includes index 1 and excludes index 3. Direct slicing must stay in range; amounts.get(1..3) returns an optional slice when the range is not already known to be valid.
A vector’s .remove(index) shifts later elements left. That is suitable for deleting an item from a sequence, but unsuitable for clearing a fixed February slot. Clear that slot with months[1] = None instead.
10. Text, Unicode, and FileMaker value lists
10.1 String versus &str
fn greeting(name: &str) -> String {
format!("Hello, {name}")
}
let owned_name = String::from("Dimitris");
let message = greeting(&owned_name);
let another = greeting("Maria");
String owns its text storage. &str borrows text. A function that only reads text usually accepts &str, allowing both owned strings and literals. See UTF-8 Strings.
10.2 Bytes, scalars, and visible characters
let name = "Δημήτρης";
assert_eq!(name.chars().count(), 8);
assert_eq!(name.len(), 16);
.len() counts UTF-8 bytes. .chars().count() counts Unicode scalar values. A user-perceived character can consist of multiple scalars, such as a letter plus a combining accent or an emoji sequence.
For an exact FileMaker text-function replacement, first define what it must count. Do not assume either Rust count reproduces every FileMaker Unicode behavior. User-perceived grapheme processing requires a suitable Unicode segmentation implementation.
You cannot use name[0] to obtain its first character. Byte slicing such as &name[0..1] may panic if it cuts inside a UTF-8 encoding. Use .chars().next() for a first scalar or a validated boundary operation. The str API documents these distinctions.
10.3 Concatenation and substitution
let customer = "C-100";
let count = 3;
let label = format!("{customer}: {count} quotes");
let corrected = label.replace("quotes", "orders");
let mut log_line = String::new();
log_line.push_str(customer);
log_line.push_str(" processed");
format! is usually the clearest equivalent of a FileMaker concatenation expression. push_str appends to an existing mutable string. replace creates a new string; it does not mutate the original.
10.4 FileMaker paragraph-delimited lists
Do not assume .lines() splits the paragraph delimiter actually present in a FileMaker value list. A carriage return is different from a line feed. Establish the delimiter and trailing-empty policy at the boundary:
let fm_list = "Alpha\rBeta\rGamma";
let values: Vec<&str> = fm_list.split('\r').collect();
assert_eq!(values, vec!["Alpha", "Beta", "Gamma"]);
If input may contain CRLF or LF, normalize deliberately. An empty string split by a delimiter yields one empty segment; some FileMaker list operations skip or interpret empty values differently. Test the exact source function’s behavior instead of asserting universal parity with GetValue, ValueCount, or List.
For a new integration contract, a JSON array is generally less ambiguous:
["Alpha", "", "Gamma"]
It explicitly preserves the empty second position, and values may contain paragraph characters without becoming accidental list boundaries.
11. Functions and explicit context
11.1 A typed script parameter
A FileMaker worker script may accept JSON, extract several properties, and calculate a result. In Rust, the internal function can take typed parameters directly:
fn has_discount(subtotal_cents: u64, threshold_cents: u64) -> bool {
subtotal_cents >= threshold_cents
}
No JSON is necessary inside this function. JSON belongs at the integration boundary. Parse once into a structure, perform ordinary typed operations, and serialize the result when leaving the component.
The signature tells the caller what to supply and what comes back. A function without a return annotation normally returns (). Use return for an early exit; otherwise, the final expression is the result.
11.2 Functions should reveal what they need
Compare a FileMaker script that reads $$CurrentUserID, the current record, and a global tax field with:
fn display_quote(account_name: &str, quote_id: &str, total_cents: u64) -> String {
format!("{account_name}: {quote_id} totals {total_cents} cents")
}
The Rust function has no hidden session dependency. That is a design choice you can also bring back to FileMaker: pass the data a worker needs rather than relying on whatever context happens to be active.
11.3 Multiple return values
fn split_total(total_cents: u64) -> (u64, u64) {
(total_cents / 100, total_cents % 100)
}
let (euros, cents) = split_total(1_250);
assert_eq!((euros, cents), (12, 50));
For two small values, a tuple is adequate. For a public interface with six amounts, use a named struct so callers do not need to remember which position is the tax amount.
11.4 No overloading by argument list
You do not define two ordinary functions with the same name in one module solely by changing parameter types. Use a generic function, different names, a trait, or associated methods when appropriate. Keep the first implementation concrete until a real second use case justifies generalization.
12. Ownership, borrowing, and lifetimes
12.1 Why a FileMaker developer encounters this
FileMaker normally hides allocation and cleanup. Rust exposes enough information for its compiler to check access to memory and resources. The resulting errors often appear before you have written any visibly “low-level” code.
Read a signature as an access contract:
| Parameter | Caller is granting |
|---|---|
name: String | Ownership of a string value |
name: &str | Shared access to text for the required duration |
name: &mut String | Exclusive access permitting modification |
quantity: u32 | A copy of a small copyable integer |
Start with this table whenever the borrow checker confuses you.
12.2 Moves
let original = String::from("Q-1001");
let transferred = original;
println!("{transferred}");
// println!("{original}"); // Intentionally rejected if uncommented.
For String, assignment transfers ownership. The original binding is no longer usable as that owned string. This avoids two independent owners both attempting to release the same allocation. See What Is Ownership?.
12.3 Copy and Clone
let first_count = 3_u32;
let second_count = first_count;
assert_eq!(first_count, second_count);
let first_id = String::from("Q-1001");
let second_id = first_id.clone();
assert_eq!(first_id, second_id);
u32 implements Copy, so using the assignment does not invalidate the original. String implements Clone; .clone() creates another owned string and copies its text allocation. The meaning and cost of cloning depend on the type. Cloning an Arc<T>, for example, increments a shared ownership count instead of cloning T.
Avoid adding .clone() everywhere just to silence errors. First ask whether the receiving function really needs ownership. Cloning a small request ID into an independent response is often a reasonable, clear choice.
12.4 Shared borrowing
fn print_id(id: &str) {
println!("{id}");
}
let id = String::from("Q-1001");
print_id(&id);
print_id(&id);
println!("Still owned here: {id}");
The called function borrows the string. It cannot consume the caller’s ownership through this reference.
12.5 Exclusive borrowing
fn add_revision(id: &mut String) {
id.push_str("-R1");
}
let mut id = String::from("Q-1001");
add_revision(&mut id);
assert_eq!(id, "Q-1001-R1");
Ordinary shared and mutable references follow access rules: while a mutable borrow of data is in use, competing access to that data is restricted. Multiple shared references are permitted when they do not conflict with exclusive access. Borrow durations are often inferred from actual use rather than simply extending to the closing brace. See References and Borrowing.
12.6 Why this prevents real problems
Intentionally rejected example:
let mut ids = vec![String::from("Q-1001")];
let first = &ids[0];
ids.push(String::from("Q-1002"));
println!("{first}");
Growing the vector might move its storage. The existing reference might then point to the wrong location. Rust rejects this overlapping use.
One correction is to finish the read before changing the collection:
let mut ids = vec![String::from("Q-1001")];
println!("{}", &ids[0]);
ids.push(String::from("Q-1002"));
Another is to clone the first ID when an independent snapshot is what the application requires. Select the correction from the intended semantics.
12.7 Slices avoid unnecessary ownership
fn count_nonzero(amounts: &[u64]) -> usize {
amounts.iter().filter(|amount| **amount != 0).count()
}
let fixed = [100, 0, 300];
let dynamic = vec![100, 0, 300];
assert_eq!(count_nonzero(&fixed), 2);
assert_eq!(count_nonzero(&dynamic), 2);
A slice borrows a contiguous sequence. It works with both arrays and vectors. The double dereference in this particular filter closure comes from borrowing the iterator’s already borrowed item. You do not need that spelling in every closure. See The Slice Type.
12.8 Lifetimes describe reference relationships
fn preferred_label<'a>(primary: &'a str, fallback: &'a str) -> &'a str {
if primary.is_empty() { fallback } else { primary }
}
'a relates the validity of the returned reference to the borrowed inputs. It does not extend the lifetime of either string, copy the text, or allocate storage. Most functions can rely on inferred lifetime rules; you write annotations when the compiler needs a relationship expressed explicitly.
For an owned result, the alternative is:
fn owned_label(primary: &str, fallback: &str) -> String {
if primary.is_empty() { fallback.to_owned() } else { primary.to_owned() }
}
This copies the selected text and returns independent ownership. For many business integration components, that is the simpler interface. See Validating References with Lifetimes.
12.9 Memory ownership is not database locking
A mutable borrow controls access to an in-process value. It does not lock a FileMaker record, reserve a database row, enforce a tenant privilege, or prevent another process from changing the source record. A cloned record-shaped struct is a snapshot, not another live pointer into FileMaker.
13. Structs, methods, enums, and business states
13.1 Named fields
#[derive(Debug, Clone)]
struct Customer {
id: String,
display_name: String,
credit_limit_cents: u64,
}
let customer = Customer {
id: "C-100".to_owned(),
display_name: "Example Customer".to_owned(),
credit_limit_cents: 500_000,
};
The definition is a type. customer is one value of that type. derive requests generated trait implementations. Debug supports developer-oriented formatting such as {:?}; it is not the same as a user-facing display label. See Defining Structs.
13.2 Methods
impl Customer {
fn label(&self) -> String {
format!("{} — {}", self.id, self.display_name)
}
fn set_credit_limit(&mut self, cents: u64) {
self.credit_limit_cents = cents;
}
fn into_id(self) -> String {
self.id
}
}
&self reads, &mut self permits modification, and self takes ownership. into_id consumes the customer value and returns its owned ID. An associated function such as Customer::new(...) has no self parameter. See Methods.
13.3 Tuple structs and distinct identifiers
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct CustomerId(String);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct QuoteId(String);
fn load_customer(id: CustomerId) {
println!("Loading {}", id.0);
}
A QuoteId cannot accidentally be supplied where a CustomerId is required. This is called a newtype pattern. By contrast, type CustomerId = String; creates an alias and does not create that distinction. Private fields plus a validating constructor can enforce stronger invariants.
The other basic struct form is a unit-like struct, such as struct QuoteValidator;. It carries no fields and can be useful as a marker or behavior-providing type. A tuple struct has numbered fields; a named-field struct gives each field a name. Choose from those forms according to what the value represents.
13.4 Enums represent alternatives
enum QuoteState {
Draft,
Approved { approved_by: String },
Sent { recipient: String },
Rejected { reason: String },
}
fn state_label(state: &QuoteState) -> &str {
match state {
QuoteState::Draft => "Draft",
QuoteState::Approved { .. } => "Approved",
QuoteState::Sent { .. } => "Sent",
QuoteState::Rejected { .. } => "Rejected",
}
}
Unlike several independent checkbox flags, one enum value has one variant at a time. Variant-specific data belongs with that variant. However, the type alone does not establish that an approver is authorized or that a recipient address is valid. Those remain business checks. See Defining an Enum.
13.5 Composition instead of class inheritance
Rust does not use a class inheritance hierarchy for structs. Put reusable data inside another struct and define shared behavior with traits. An Address field inside Customer is composition. Avoid creating a broad “base record” abstraction merely because multiple FileMaker tables share an ID and audit columns.
14. Collections, finding, sorting, and grouping
14.1 Choose a collection from the operation
| Collection | Useful for | Important behavior |
|---|---|---|
Vec<T> | Ordered rows, lines, batches | Preserves sequence; position is not identity |
HashMap<K, V> | Look up one value by key | Iteration order is not a reporting sort order |
HashSet<T> | Membership and duplicate detection | Stores distinct values; no useful reporting order |
BTreeMap<K, V> | Key-ordered lookup and traversal | Ordered by the key’s Rust ordering |
BTreeSet<T> | Sorted distinct values | Order still follows the chosen type’s comparison |
VecDeque<T> | Queue processing | Efficient operations at both ends |
BinaryHeap<T> | Priority selection | Useful for repeatedly obtaining the largest-priority item |
Start with Vec or HashMap for ordinary in-memory work. These are not database indexes and do not provide persistence. See the standard collection guide.
14.2 Find one or filter many
#[derive(Debug)]
struct QuoteSummary {
id: String,
customer_id: String,
total_cents: u64,
}
let quotes = vec![
QuoteSummary { id: "Q-1".into(), customer_id: "C-1".into(), total_cents: 100 },
QuoteSummary { id: "Q-2".into(), customer_id: "C-2".into(), total_cents: 200 },
];
let found = quotes.iter().find(|quote| quote.id == "Q-2");
assert!(found.is_some());
let selected: Vec<&QuoteSummary> = quotes.iter()
.filter(|quote| quote.customer_id == "C-1")
.collect();
assert_eq!(selected.len(), 1);
This scans values already loaded in memory. It does not send a FileMaker find request or enforce record-level access. Vec<&QuoteSummary> borrows selected values; those references cannot outlive their source collection.
14.3 Sorting
let mut amounts = vec![300_u64, 100, 200];
amounts.sort();
assert_eq!(amounts, vec![100, 200, 300]);
amounts.sort_by(|left, right| right.cmp(left));
For rows, quotes.sort_by_key(|quote| quote.total_cents) sorts by a field when the collection is mutable. Sorting changes sequence; it must not change your record identity model. For floating-point fields, handle NaN and your domain policy deliberately rather than unwrapping an optional comparison.
14.4 Grouping with a map
use std::collections::HashMap;
let rows = [("C-1", 100_u64), ("C-2", 200), ("C-1", 300)];
let mut counts: HashMap<&str, usize> = HashMap::new();
for (customer_id, _) in rows {
*counts.entry(customer_id).or_insert(0) += 1;
}
assert_eq!(counts.get("C-1"), Some(&2));
entry combines lookup and insertion. The * accesses the value behind the returned mutable reference. If grouping money, apply checked addition instead of copying this small counter example uncritically. See Hash Maps.
14.5 Relationships do not appear automatically
An Invoice { customer_id } value stores a key. To obtain the customer, your code must query a database, call an API, or look up a preloaded map. There is no implicit FileMaker table-occurrence traversal.
For a batch of invoices, fetch authorized data in a suitable batch and build a map rather than making one remote customer request per invoice. This avoids an N+1 network pattern, but cache freshness and access control must still be defined.
15. Errors, optional values, and validation
15.1 Absence and failure are different
let optional_email: Option<String> = None;
let parsed_quantity: Result<u32, _> = "twelve".parse();
assert!(optional_email.is_none());
assert!(parsed_quantity.is_err());
None may be a valid absence. Err reports an operation that failed. Do not return an empty string for both “customer has no email” and “database connection failed.” The caller needs different actions.
15.2 Result<T, E>
fn quantity(text: &str) -> Result<u32, std::num::ParseIntError> {
text.parse()
}
match quantity("12") {
Ok(value) => println!("Quantity: {value}"),
Err(error) => eprintln!("Invalid quantity: {error}"),
}
The result carries success data or an error. There is no shared Get(LastError) register to read after another operation has potentially changed it. See Recoverable Errors with Result.
15.3 ? propagates a failure
fn double_quantity(text: &str) -> Result<u64, std::num::ParseIntError> {
let value: u32 = text.parse()?;
Ok(u64::from(value) * 2)
}
On success, ? extracts the value. On failure, it returns early with a compatible error. In an Option-returning function it similarly propagates None. It does not ignore errors or retry operations.
15.4 Choosing the error type
| Situation | Practical error design |
|---|---|
| Small internal utility with one failure family | Return the concrete library error |
| Business operation with named failure cases | Define a domain error enum or structured error |
| Executable entry point combining unrelated failures | A boxed error can be a simple boundary choice |
| JSON service | Stable public error code plus a controlled message |
Do not expose a database password, filesystem path, or raw upstream response in the public error message. Log diagnostic detail only through an appropriate, access-controlled logging policy.
15.5 unwrap, expect, and panic
unwrap() and expect(...) panic when a result is an error or an option is absent. They are useful in tests and some established invariants. They are poor substitutes for validating request data.
A panic is not an ordinary domain failure. Depending on build configuration and runtime circumstances, it may unwind a thread or abort the process. Do not design an HTTP validation contract around catching panics. Return a result instead.
15.6 Structural validity is only the first layer
Deserializing quantity: u32 rejects a JSON string or a negative integer, but it accepts zero. The business rule “quantity must be positive” needs another check. Similarly, a string-typed customer ID does not prove that the customer exists or that the caller may access it.
For the tutorial service, the stages are:
- Bound the input size.
- Parse JSON into a typed request.
- Validate version, currency, IDs, rates, and line limits.
- Perform checked arithmetic.
- Return a stable response envelope.
The service does not access customer records, so record authorization is outside its current contract.
16. Generics, traits, closures, and programming styles
16.1 Generics
fn first<T>(values: &[T]) -> Option<&T> {
values.first()
}
assert_eq!(first(&[10, 20]), Some(&10));
assert_eq!(first(&["A", "B"]), Some(&"A"));
T is a placeholder for a concrete type selected by use. The compiler checks that the function uses operations available for that type. This is not a dynamically typed “anything” field. See Generic Data Types.
16.2 Traits
trait Label {
fn label(&self) -> String;
}
struct QuoteRef {
id: String,
}
impl Label for QuoteRef {
fn label(&self) -> String {
format!("Quote {}", self.id)
}
}
fn render_label(value: &impl Label) -> String {
value.label()
}
A trait defines behavior a type provides. It can express a common interface for an API-backed repository and an in-memory repository used by tests. It does not add a relationship graph or database engine.
&impl Label uses a generic parameter behind the concise syntax. &dyn Label uses a trait object for runtime dispatch when the trait is dyn-compatible. Use runtime dispatch when you need heterogeneous implementations selected at runtime, rather than introducing it automatically. See Traits.
16.3 Closures
let minimum = 100_u64;
let is_large = |amount: u64| amount >= minimum;
assert!(is_large(150));
A closure is an anonymous callable that can capture values from its environment. Its capture behavior depends on how those values are used. A move closure takes ownership of captured values, although copyable values are copied. The Fn, FnMut, and FnOnce traits describe different calling capabilities. See Closures.
16.4 Iterators
let amounts = [0_u64, 100, 250, 0, 400];
let selected: Vec<u64> = amounts.iter()
.copied()
.filter(|amount| *amount > 0)
.map(|amount| amount * 2)
.collect();
assert_eq!(selected, vec![200, 500, 800]);
The pipeline reads, copies the small integers, filters, transforms, and collects. Iterator adapters are lazy until consumed. .sum(), .count(), .collect(), and a for loop are examples of consumers. See Iterators.
| Method | Ownership behavior |
|---|---|
collection.iter() | Produces shared references |
collection.iter_mut() | Produces mutable references |
vector.into_iter() on an owned vector | Consumes the vector and produces owned elements |
The precise IntoIterator behavior depends on the receiver type. Read the type, not just the method name. An iterator pipeline does not automatically make processing parallel.
16.5 Which programming “school” is Rust?
Rust is multi-paradigm. Use the style that makes the rule easiest to verify.
| Style | Rust expression | FileMaker bridge |
|---|---|---|
| Imperative | Mutable variables and explicit loops | Script steps and loop processing |
| Functional | Expressions, closures, iterators, immutable transformations | Composed calculations and custom functions |
| Data-oriented | Structs and collections arranged around operations | Batch extraction and processing of selected fields |
| Interface-oriented | Traits and implementations | An explicit contract used by interchangeable worker implementations |
| State modeling | Enums and validated transitions | Replace loosely coordinated flags with defined business states |
A short, explicit for loop is not inferior to an iterator chain. For the quote calculator, the loop makes validation order and early failure clear. Keep abstractions proportional to the actual component.
17. Modules, crates, dependencies, and documentation
17.1 Vocabulary
| Term | Meaning |
|---|---|
| Package | Cargo-managed project described by a manifest |
| Crate | A compilation unit, such as a library or executable |
| Module | A namespace and privacy boundary within a crate |
| Workspace | A Cargo arrangement containing multiple packages |
| Dependency | A package used by your package |
| Feature | A named compile-time capability or optional dependency selection |
A package can contain a library crate and multiple binary crates. Our project does exactly that: one calculator library plus CLI and HTTP executables.
17.2 Splitting source files
// src/lib.rs
pub mod money;
// src/money.rs
pub fn is_zero(cents: u64) -> bool {
cents == 0
}
mod declares a module. use brings a path into scope. It is not the equivalent of performing a script. Items are private unless their visibility is widened; pub(crate) exposes an item inside the crate without making it part of the external public API. See Modules and Privacy.
17.3 Optional features
Our manifest defines:
[features]
default = []
http = ["dep:axum", "dep:tokio"]
The core CLI does not need the HTTP framework enabled. cargo run --features http --bin quote-http enables the optional service. #[cfg(feature = "http")] conditionally includes the HTTP module. See Cargo Features.
17.4 Documentation belongs with the contract
Document units, absence rules, rounding, side effects, and errors. “Calculates a quote” is less useful than “Rounds discount to whole cents, subtracts it, then rounds tax on the discounted subtotal.”
Use /// for public-item documentation and //! for containing-module or crate documentation. Rust documentation can include code examples that cargo test checks as documentation tests when appropriately written. A comment describes intent; a test supplies executable evidence for selected cases.
18. Advanced structures: smart pointers, async, macros, and unsafe
This chapter is a recognition guide. None of these constructs is a prerequisite for writing the first pure business function.
18.1 Smart pointers and interior mutability
| Type | Purpose | Important limit |
|---|---|---|
Box<T> | Own a heap-allocated value, including recursive structure elements | Does not provide shared ownership |
Rc<T> | Reference-counted shared ownership in one thread | Not for cross-thread sharing |
Arc<T> | Atomic reference-counted shared ownership | Does not by itself make mutable access safe |
RefCell<T> | Runtime-checked borrowing in one thread | Invalid borrowing can panic; checked APIs can return errors |
Mutex<T> | Protect shared access with a lock | Can block and participate in deadlocks |
RwLock<T> | Coordinate multiple readers or one writer | Locking policy and deadlocks still need design |
Weak<T> | Non-owning reference to reference-counted data | Upgrade may fail after owners disappear |
Read Box, Rc, and RefCell. Start with ordinary owned structs. Do not build every business object as Rc<RefCell<T>> to imitate a mutable global object graph.
A recursive tree can use a box to give the compiler a finite-sized pointer where direct recursive storage would be impossible:
enum Rule {
Always,
Not(Box<Rule>),
All(Vec<Rule>),
}
18.2 Threads are not PSoS
let worker = std::thread::spawn(|| 21 * 2);
let value = worker.join().expect("Teaching worker did not panic");
assert_eq!(value, 42);
This starts an operating-system thread inside the Rust process. It does not authenticate to FileMaker or create a server-side FileMaker session. A panic in the worker is reported through the join result. See Threads.
Send and Sync describe type capabilities relevant to moving values across threads and sharing references. Rust prevents data races in sound safe code, but it does not prevent every race condition: two valid requests can still read stale business data and make conflicting decisions.
18.3 Shared state
Use a channel to transfer work or coordinate access with an appropriate synchronization type. Arc<Mutex<T>> is one familiar shared mutable pattern, not a mandatory default. A mutex is not a database transaction. Avoid holding a blocking lock while waiting for unrelated network operations. See Shared-State Concurrency.
18.4 Async and await
An async fn produces a future. An executor polls futures; .await may suspend the current async task while an operation is pending. This is valuable for handling many I/O waits. It does not automatically make CPU calculations run in parallel or make a FileMaker client call nonblocking.
Our HTTP binary uses Tokio as the runtime and Axum as the web framework. A large CPU-heavy transformation should use a bounded worker strategy rather than occupying async executor threads indefinitely. A synchronous FileMaker Insert from URL still waits for the response even when the Rust handler is asynchronous. See Futures and Async Syntax.
18.5 Macros and attributes
println!, format!, and vec! are macros. #[derive(Debug)] and #[test] are attributes. Serde’s derive support generates serialization/deserialization implementations. These are compile-time facilities, not runtime evaluation of FileMaker calculation text.
Recognize macro_rules! as a declarative macro definition and procedural macros as compiler extensions supplied by suitable crates. You can use the language effectively for a long time without writing either kind yourself.
18.6 Unsafe, raw pointers, unions, and FFI
Rust supports raw pointers such as *const T and *mut T, union types for overlapping storage, and foreign-function interfaces. These are mainly relevant when interfacing with native code, operating-system APIs, or binary formats requiring explicit layout.
unsafe permits specific operations with correctness obligations the compiler cannot establish. It does not turn off all type or borrow checking. Safe callers depend on unsafe implementations upholding their contracts. See Unsafe Rust.
A Rust cdylib is not automatically a FileMaker plug-in. A plug-in must satisfy Claris’s SDK ABI, lifecycle, registration, memory, and thread requirements. Exported extern "C" functions alone do not provide that integration. Start with HTTP or a command-line boundary unless a native plug-in is specifically required.
18.7 Types you may encounter later
| Construct | Recognize it as |
|---|---|
! in a type position | The never type, for computations that do not return normally |
fn(A) -> B | A function pointer type |
dyn Trait | A dynamically dispatched trait object |
impl Trait in a return position | An opaque concrete type implementing the stated trait bounds |
Cow<'a, str> | Borrowed-or-owned text, useful when allocation is conditional |
Pin<P> | A pinned pointer wrapper used by address-sensitive APIs, including some futures |
PhantomData<T> | Type-level ownership/variance/drop-related information without storing a T value |
MaybeUninit<T> | Low-level storage that may not yet contain a valid initialized T |
These are not alternative database field types to adopt indiscriminately. Consult the specific API’s safety and behavior contract before using the low-level entries. The Rust Reference type overview supplies the broader taxonomy.
19. A complete quote-calculation project
19.1 What we are building
The companion rust-filemaker-lab package contains a shared calculator with two interfaces:
quote-cli: reads one JSON request from standard input and writes one JSON response to standard output.quote-http: accepts the same request over a token-protected loopback HTTP endpoint.
The component does not query FileMaker, commit records, or keep business state. This makes its calculation behavior independent of a layout, account session, database connection, or current found set.
| File | Responsibility |
|---|---|
Cargo.toml | Package definition, dependency ranges, optional HTTP feature |
Cargo.lock | Exact dependency resolution used for validation |
src/lib.rs | Request types, response types, validation, arithmetic |
src/bin/quote-cli.rs | Bounded standard-input adapter and exit codes |
src/http.rs | Routes, token check, JSON handling, HTTP status mapping |
src/bin/quote-http.rs | Service configuration, listener, shutdown |
tests/quote_contract.rs | Business and JSON contract tests |
tests/http_contract.rs | HTTP adapter tests |
examples/request.json | Reproducible request |
filemaker/Call_Rust_Quote.txt | FileMaker script reconstruction guide |
VALIDATION.md | Exact checks completed and limitations |
The full source is in the downloadable project. A source appendix below reproduces the main implementation so this tutorial can also be studied independently.
19.2 The request contract
{
"schema_version": 1,
"quote_id": "Q-1001",
"currency": "EUR",
"discount_bps": 1000,
"tax_bps": 2400,
"lines": [
{ "quantity": 2, "unit_cents": 1250 },
{ "quantity": 1, "unit_cents": 500 }
]
}
This is a teaching contract with explicit boundaries:
| Input | Accepted values |
|---|---|
schema_version | Exactly 1 |
quote_id | Nonblank, at most 128 UTF-8 bytes; returned unchanged |
currency | Exactly EUR |
discount_bps, tax_bps | Whole numbers from 0 through 10,000 |
lines | From 1 through 1,000 entries |
quantity | Whole number from 1 through 1,000,000 |
unit_cents | Nonnegative integer within the supported amount range |
| Entire request | At most 256 KiB of input bytes |
Unknown properties are rejected by #[serde(deny_unknown_fields)]. This catches spelling mistakes such as tax_bp instead of tax_bps. Strict rejection is a chosen API evolution policy, not a universal rule: an API designed to tolerate additive properties would use a different policy.
The service also caps amounts at 9_007_199_254_740_991, the common binary64 safe-integer upper bound. This is a conservative interoperability choice for clients that might represent JSON numbers with binary64, not a statement that u64 stops there. See the f64 precision documentation. An API using decimal-string amounts would need a different contract.
19.3 The calculation policy
- Calculate each line as whole quantity multiplied by unit cents.
- Sum all lines into the subtotal.
- Calculate the discount on the subtotal, rounding to whole cents with nonnegative half-up rounding.
- Subtract the discount to obtain the net amount.
- Calculate tax on the net amount, using the same rounding rule.
- Add net and tax to obtain the total.
For the example:
| Stage | Calculation | Cents |
|---|---|---|
| First line | 2 × 1,250 | 2,500 |
| Second line | 1 × 500 | 500 |
| Subtotal | 2,500 + 500 | 3,000 |
| Discount | 3,000 × 10% | 300 |
| Net | 3,000 − 300 | 2,700 |
| Tax | 2,700 × 24% | 648 |
| Total | 2,700 + 648 | 3,348 |
This is a documented example policy. It is not tax or accounting guidance and should not be assumed to reproduce an existing solution that rounds per line or uses another discount/tax order.
19.4 Why the intermediate calculation uses u128
To round a nonnegative basis-point calculation, we use:
let rounded = (u128::from(amount) * u128::from(bps) + 5_000) / 10_000;
Adding half the denominator implements the stated tie-up rule for nonnegative values. The wider intermediate avoids overflowing the multiplication even when the final amount fits the allowed output range. Conversion back to u64 and the supported-range check remain explicit.
This formula is not a drop-in rounding rule for negative credit amounts. Our request model excludes negative prices. To support credits, define signed amount handling and a signed rounding policy, then test both signs and tie cases.
19.5 Deserialization
Serde’s Deserialize derive turns a compatible JSON representation into the typed request. Serialize turns response types into JSON. They are separate traits; a type can implement one or both. See Serde’s derive documentation.
For example, the input "quantity": "2" contains a JSON string and is rejected where u32 is expected. Explicit JSON types matter when using FileMaker’s JSONSetElement. A number-looking string is still a string at the boundary.
19.6 Response envelopes
Success:
{
"status": "ok",
"data": {
"quote_id": "Q-1001",
"currency": "EUR",
"subtotal_cents": 3000,
"discount_cents": 300,
"net_cents": 2700,
"tax_cents": 648,
"total_cents": 3348
}
}
Business failure:
{
"status": "error",
"error": {
"code": "invalid_quantity",
"message": "Line 1: quantity must be 1..=1000000"
}
}
The internal Rust enum makes success and error mutually exclusive. Serde’s internally tagged representation exposes that choice through status. A caller branches on the stable code and status rather than parsing the English sentence.
19.7 Run the CLI
In Bash, zsh, or another shell with conventional input redirection:
cargo run --locked --bin quote-cli < examples/request.json
In PowerShell:
Get-Content -Raw -Encoding utf8 .\examples\request.json |
cargo run --locked --bin quote-cli
The supplied sample is ASCII, so the PowerShell text pipeline is suitable for it. For arbitrary multilingual binary-exact input, verify your PowerShell version’s native-process encoding or use an explicit byte-preserving process adapter.
| CLI exit code | Meaning |
|---|---|
0 | A successful JSON result was emitted |
2 | The request was rejected and a structured JSON error was emitted |
1 | An I/O or serialization failure prevented normal processing |
Normal JSON output goes to stdout. Operational diagnostics go to stderr. This separation matters when another program consumes the JSON. The CLI reads no more than the body limit plus one byte, allowing oversized input to be detected without first loading an unbounded document. See Read::take.
19.8 Run the HTTP service
Use a private, randomly generated alphanumeric token of at least 32 characters. The following literal is a public demonstration value; replace it in real use.
Bash/zsh:
export APP_TOKEN='0123456789abcdef0123456789abcdef'
cargo run --locked --features http --bin quote-http
PowerShell:
$env:APP_TOKEN = '0123456789abcdef0123456789abcdef'
cargo run --locked --features http --bin quote-http
The service binds to 127.0.0.1:8787. In another terminal, on the same machine:
curl --silent --show-error \
--header 'Content-Type: application/json' \
--header 'X-FM-Token: 0123456789abcdef0123456789abcdef' \
--data-binary @examples/request.json \
http://127.0.0.1:8787/v1/quote
In PowerShell, invoke curl.exe when you intend to use the native curl command, and put the options on one line or use PowerShell continuation syntax. Backslash continuation in the listing above is shell-specific.
19.9 HTTP behavior
Condition on /v1/quote POST | Status | Envelope |
|---|---|---|
| Valid request and token | 200 | status: "ok" |
| Missing or incorrect token | 401 | unauthorized |
| Malformed JSON syntax | 400 | invalid_json |
| Wrong content type | 415 | invalid_json |
| JSON fields do not match request types | 422 | invalid_json |
| Valid structure, invalid business values | 422 | Specific business error code |
| Body exceeds configured limit | 413 | payload_too_large |
The JSON extractor is last in the handler’s argument list because it consumes the request body. Using Result<Json<QuoteRequest>, JsonRejection> allows the handler to map extraction errors into its response envelope. Axum’s Json documentation describes the extractor, and DefaultBodyLimit configures the bound used here.
The table applies to the intended route and method. The unauthenticated /health route returns the plain text ok; it exposes no business state. Default responses to unknown routes or unsupported methods are not promised to use the application envelope. The FileMaker caller must therefore handle a non-JSON response.
19.10 What this service deliberately leaves for production engineering
The sample has no database, durable queue, central secret management, distributed rate limiting, TLS listener, full observability system, or installation service definition. Its token comparison uses ordinary string equality; it is not presented as a constant-time authentication implementation. The body is extracted before the handler executes its token decision, so authentication is not an early streaming rejection layer. The input bound limits a single body, not the number of simultaneous connections.
These are concrete limits of a teaching adapter. Before expanding its exposure or workload, define appropriate admission controls, authentication, TLS termination, process supervision, and resource limits. The business library can remain unchanged while the transport adapter is hardened.
20. Calling Rust from FileMaker
20.1 Choose an integration boundary
| Method | When it fits | Responsibility you must supply |
|---|---|---|
| Local HTTP service | Client or server needs an explicit JSON call | Install/start service, protect endpoint, handle timeouts |
| Hosted HTTPS service | Several clients share a component | Authentication, authorization, TLS, availability, capacity |
| CLI process | Batch job, scheduler, or an available process-launch adapter | Launch process, capture stdout/stderr/exit, quoting, permissions |
| Native FileMaker plug-in | Direct in-process API is specifically required | Full SDK/ABI implementation and platform packaging |
| WebAssembly in a Web Viewer | Browser-compatible computation is appropriate | Compile target, JavaScript bridge, browser constraints |
Rust itself does not add a universal FileMaker “run this executable and capture stdout” step. A CLI integration needs an actual supported launcher or adapter appropriate to the deployment. This tutorial uses Insert from URL, a native documented FileMaker boundary.
20.2 Where localhost actually points
| Script execution environment | 127.0.0.1 refers to |
|---|---|
| FileMaker Pro client | The user’s computer |
| FileMaker Go | The iPhone or iPad |
| PSoS worker or server schedule | The server-side execution host |
| WebDirect server-side execution | The relevant server-side execution host |
| A containerized process | That container’s network namespace unless configured otherwise |
If Rust runs on your workstation and PSoS calls 127.0.0.1, the request does not go back to your workstation. Put the service on the worker’s host or use an explicitly configured reachable HTTPS endpoint.
Server-side FileMaker scripts have their own sessions and do not inherit the client’s layout, found set, variables, or global field values. Pass needed context explicitly. See Running Scripts on Server and Perform Script On Server.
20.3 Build JSON with explicit types
The included FileMaker script builds the exact sample request with JSONSetElement, using JSONNumber, JSONString, and JSONArray. In a real solution, replace the sample constants with validated values from an explicitly established record context.
For a repeating field, preserve the declared slots. For a related set of quote lines, preserve stable line identifiers where needed and include only the records the current account may send. Do not equate “visible in a portal” with a fully defined export contract.
If a FileMaker amount is stored in euros, define how it is converted to whole cents. Merely multiplying by 100 without a rounding/validation policy may send fractions where the Rust API requires an integer. The teaching script uses integer-cent constants to avoid hiding that decision.
20.4 Send the body by variable reference
In FileMaker cURL options:
"--request POST --header " & Quote ( "Content-Type: application/json" ) &
" --header " & Quote ( "X-FM-Token: " & $token ) &
" --data-binary @$request --dump-header $responseHeaders" &
" --connect-timeout 2 --max-time 10 --noproxy 127.0.0.1 --show-error"
Here @$request is FileMaker’s variable-backed data source, not a shell request to read a local file. $responseHeaders is a destination variable for headers. The token is restricted to ASCII letters/digits before building the header. See Supported cURL Options and Insert from URL.
The URL is plain HTTP only because this teaching service is bound to the local loopback interface. For a remote endpoint, use HTTPS with certificate verification and a deployment-appropriate authentication design. Do not use --insecure as a connection fix.
20.5 Check transport, protocol, and application outcomes
A request can fail at several different levels:
| Level | Example | Appropriate handling |
|---|---|---|
| Connection | Rust service is stopped | Report unavailability; follow a defined retry policy |
| HTTP | 401 or 413 | Inspect status/diagnostics and any structured error body |
| Protocol | Proxy returns HTML instead of JSON | Reject unexpected content |
| Contract | JSON has an unexpected envelope or wrong field type | Reject the response |
| Business | Quantity is zero | Show or process the domain error |
| Persistence | Record changed while calculation ran | Reconcile/revalidate before saving |
Capture Get(LastError) and Get(LastErrorDetail) immediately after Insert from URL. FileMaker’s cURL error behavior depends on the options and HTTP response; do not assume error zero means business success. With --show-error, an HTTP error may also produce a FileMaker error while still supplying a useful JSON body.
The included script captures both error functions in one Let calculation, validates JSON, preserves a valid application error, rejects a failed transport on a purported success, and checks expected success fields. JSONGetElementType distinguishes a numeric total from a string that happens to contain digits.
The saved response headers are available for diagnostics. A generalized HTTP status parser must handle the final relevant header block rather than assume the first status line always describes the final response.
20.6 Full Script Workspace reconstruction guide
#Call Rust Quote — Script Workspace reconstruction guide
#Script parameter: the same private token configured as APP_TOKEN for the Rust service.
#Run the script on the machine where the service is listening on 127.0.0.1:8787.
#This listing is an importable .fmscript file.
Set Error Capture [ On ]
Set Variable [ $token ; Value: Get ( ScriptParameter ) ]
If [ Length ( $token ) < 32 or not Exact ( Filter ( $token ; "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" ) ; $token ) ]
Exit Script [ Text Result: JSONSetElement ( "{}" ;
[ "status" ; "error" ; JSONString ] ;
[ "error.code" ; "invalid_configuration" ; JSONString ] ;
[ "error.message" ; "A service token of at least 32 ASCII letters or digits is required" ; JSONString ]
) ]
End If
Set Variable [ $request ; Value: JSONSetElement ( "{}" ;
[ "schema_version" ; 1 ; JSONNumber ] ;
[ "quote_id" ; "Q-1001" ; JSONString ] ;
[ "currency" ; "EUR" ; JSONString ] ;
[ "discount_bps" ; 1000 ; JSONNumber ] ;
[ "tax_bps" ; 2400 ; JSONNumber ] ;
[ "lines" ; "[]" ; JSONArray ] ;
[ "lines[0].quantity" ; 2 ; JSONNumber ] ;
[ "lines[0].unit_cents" ; 1250 ; JSONNumber ] ;
[ "lines[1].quantity" ; 1 ; JSONNumber ] ;
[ "lines[1].unit_cents" ; 500 ; JSONNumber ]
) ]
Set Variable [ $response ; Value: "" ]
Set Variable [ $responseHeaders ; Value: "" ]
Set Variable [ $curl ; Value:
"--request POST --header " & Quote ( "Content-Type: application/json" ) &
" --header " & Quote ( "X-FM-Token: " & $token ) &
" --data-binary @$request --dump-header $responseHeaders" &
" --connect-timeout 2 --max-time 10 --noproxy 127.0.0.1 --show-error"
]
Insert from URL [ Select entire contents ; With dialog: Off ; Target: $response ;
"http://127.0.0.1:8787/v1/quote" ; Verify SSL Certificates ; cURL options: $curl ]
# Capture both functions in the immediately following step.
Set Variable [ $callError ; Value: Let (
[ number = Get ( LastError ) ; detail = Get ( LastErrorDetail ) ] ;
JSONSetElement ( "{}" ;
[ "number" ; number ; JSONNumber ] ;
[ "detail" ; detail ; JSONString ]
)
) ]
If [ IsEmpty ( $response ) or Left ( JSONFormatElements ( $response ) ; 1 ) = "?" ]
Exit Script [ Text Result: JSONSetElement ( "{}" ;
[ "status" ; "error" ; JSONString ] ;
[ "error.code" ; "transport_or_protocol_error" ; JSONString ] ;
[ "error.message" ; "No valid JSON response was received" ; JSONString ] ;
[ "error.filemaker_code" ; JSONGetElement ( $callError ; "number" ) ; JSONNumber ]
) ]
End If
# A valid application error remains useful even when HTTP status causes a FileMaker error.
If [ JSONGetElement ( $response ; "status" ) = "error" ]
Exit Script [ Text Result: $response ]
End If
If [ JSONGetElement ( $callError ; "number" ) <> 0 ]
Exit Script [ Text Result: JSONSetElement ( "{}" ;
[ "status" ; "error" ; JSONString ] ;
[ "error.code" ; "transport_error" ; JSONString ] ;
[ "error.message" ; "The URL operation reported an error" ; JSONString ] ;
[ "error.filemaker_code" ; JSONGetElement ( $callError ; "number" ) ; JSONNumber ]
) ]
End If
If [ JSONGetElement ( $response ; "status" ) <> "ok" or
not Exact ( JSONGetElement ( $response ; "data.quote_id" ) ; "Q-1001" ) or
JSONGetElementType ( $response ; "data.total_cents" ) <> JSONNumber ]
Exit Script [ Text Result: JSONSetElement ( "{}" ;
[ "status" ; "error" ; JSONString ] ;
[ "error.code" ; "protocol_error" ; JSONString ] ;
[ "error.message" ; "The response does not match the expected contract" ; JSONString ]
) ]
End If
# The sample total is 3348 cents. This worker does not write any records.
Set Variable [ $totalCents ; Value: JSONGetElement ( $response ; "data.total_cents" ) ]
Exit Script [ Text Result: $response ]
20.7 Return a result before adding persistence
The script returns the JSON envelope through Exit Script. For the example, data.total_cents is 3348; display €33.48 only at the UI boundary using your formatting policy.
Do not silently write the result into whichever quote record happens to be current after the network call. For a real write, retain the intended quote ID and relevant revision information, re-establish authorized record context, and check for source changes. The worker’s current sample ID is a correlation label, not a database write lock.
20.8 Test the boundary on the actual FileMaker host
Start the Rust service, configure the same private token in the script parameter, and run the sample locally. Then test a wrong token, a stopped service, a zero quantity, and a response timeout. If moving the worker to PSoS, repeat the connection test from the server session.
The Rust side is automated and executable in the companion project. The FileMaker script is a reviewed reconstruction guide; this deliverable does not include an executed .fmp12 test file. Do not interpret Rust test results as evidence of a FileMaker runtime test.
21. Persistence, transactions, security, and deployment
21.1 In-memory values do not persist themselves
Choose a persistence boundary explicitly:
- Let FileMaker own the records and send a minimal calculation payload to Rust.
- Let Rust use the FileMaker Data API with suitable credentials, privileges, and session handling.
- Use another database when that is an intentional part of the architecture.
The FileMaker Data API guide documents authenticated REST access to hosted records. A Rust HTTP client would still need to handle transport failures, API errors, token lifecycle, and access restrictions. This tutorial does not invent a direct FileMaker file driver or suggest opening .fmp12 storage from Rust.
21.2 Database transactions do not follow a JSON call
Suppose FileMaker creates an order and calls Rust to contact a payment provider. A FileMaker rollback cannot automatically reverse an already completed external payment.
Define the sequence, durable status, retries, and compensation for each external side effect. For a retryable write, an idempotency key means that repeating the same operation does not create another payment/order/job. A quote ID echoed by this calculator is not an implemented idempotency mechanism; the calculator is simply side-effect free.
21.3 Stale results
If a quote changes while Rust calculates its totals, the returned result may be correct for the old input. Preserve an input revision or digest and revalidate before applying the output. The current service does not store or compare revisions. A future contract can add that capability deliberately, with a versioning plan.
21.4 Memory safety and security answer different questions
Rust’s memory and concurrency rules prevent important categories of invalid memory access in sound safe code. They do not prove that the correct user requested a calculation, that an endpoint is authorized, that uploaded data is harmless, or that a third-party dependency is trustworthy.
For this architecture, useful controls follow directly from the boundary:
| Boundary | Concrete control |
|---|---|
| Client to local service | Private token, loopback listener, fixed route and schema |
| Remote caller to service | TLS, appropriate authentication/authorization, resource limits |
| Request to calculation | Type checks, size limits, business validation, checked arithmetic |
| Service to filesystem | Avoid arbitrary client paths; restrict operations if file access is added |
| Service to database | Least-privilege account, record authorization, explicit transaction policy |
| Build to release | Review dependencies and build scripts; retain the lockfile and build record |
Loopback binding limits network reachability, but it does not make other local processes trusted. Browser-accessible localhost services also need deliberate cross-origin and request-authentication design. CORS is not a substitute for authenticating non-browser callers.
Cargo build scripts can execute code during a build. Memory safety in your application does not make an arbitrary package safe to build. See Cargo Build Scripts. Select dependencies for a known purpose and review updates proportionally to their role.
21.5 Deploy the correct executable
Build an optimized binary for each supported target OS and architecture:
cargo build --locked --release --features http --bin quote-http
A Windows build does not run as a macOS application. A Linux binary may depend on the target system’s runtime/linker compatibility. Native dependencies can add packaging requirements. Do not promise “one binary everywhere” merely because the source is portable.
The normal FileMaker user does not need Cargo installed to run a compatible prebuilt executable. Your installation still needs a defined executable location, configuration, permissions, startup behavior, update process, and service health check.
21.6 Supervision and lifecycle
For a persistent component, use an operating-system-appropriate service manager and a dedicated account with the permissions it needs. Keep the token out of source control and user-facing logs. Define what the FileMaker caller should do if the component is unavailable.
The sample handles Ctrl+C with Axum’s graceful-shutdown facility. It does not include every operating-system service-manager signal or a deployment timeout policy. Review those details for the chosen host. The Axum serve API documents the serving primitive.
21.7 Performance must include the boundary
A native calculation can be fast while the overall integration is slow. Measure payload construction, serialization, network or process overhead, deserialization, computation, and result application.
Do not send one HTTP request per quote line when one bounded quote request will do. If a batch must exceed the tutorial’s limits, design a batch protocol or job interface rather than simply removing all bounds. Release builds and representative data matter more than an isolated demonstration with three integers.
22. Testing and debugging
22.1 Start with a business rule
#[test]
fn the_sample_quote_has_the_expected_total() {
let request: rust_filemaker_lab::QuoteRequest = serde_json::from_str(
include_str!("../examples/request.json")
).unwrap();
let totals = rust_filemaker_lab::calculate_quote(&request).unwrap();
assert_eq!(totals.total_cents, 3_348);
}
This listing belongs in a test file under tests/ in the companion package. The unwrap calls are appropriate because unexpected failure should fail the test. The expected total is calculated from the documented policy, not copied from the program’s output as an unquestioned oracle. See Writing Tests.
22.2 Useful test dimensions
| Category | Examples covered by the project |
|---|---|
| Normal behavior | Example subtotal, discount, tax, total |
| Rounding | Half-cent discount and tax ties |
| Bounds | Empty/excessive lines; zero/excessive quantity |
| Arithmetic | Multiplication overflow; output range cap |
| Text | Nonblank ID and preserved Unicode identifier |
| Contract | Missing fields, wrong types, negative quantities, unknown properties |
| Transport adapter | Authentication, media type, malformed JSON, body limit, status mapping |
The provided tests are a starting suite, not a proof over all inputs. For expanded money rules, add independently computed fixtures, boundary cases, and property-based tests suited to the model. For FileMaker integration, include runtime tests on the actual supported client/server versions.
22.3 Run the checks
cargo fmt --check
cargo test --locked
cargo test --locked --all-features
cargo clippy --locked --all-targets --all-features -- -D warnings
The default-feature test run checks the CLI/core configuration. The all-feature run also includes HTTP tests. A feature-specific compilation error can remain hidden if you only test the default configuration.
-D warnings treats lint warnings as failures for this check. It is useful for a maintained example; it is not proof of correct business logic or a complete vulnerability scan.
22.4 Read the first useful compiler error
| Diagnostic | Likely issue | First question |
|---|---|---|
| E0308, mismatched types | You supplied another type | Is conversion intended, or is the contract wrong? |
| E0382, moved value | Ownership transferred earlier | Should the called function borrow instead? |
| E0596, cannot borrow as mutable | Access does not permit mutation | Is mut needed at the owner and at the reference? |
| E0499/E0502, conflicting borrows | Access overlaps | Can the read finish before the write? |
| E0597, value does not live long enough | Reference outlives its data | Should the result own the data? |
| E0277, trait bound not satisfied | Required behavior is missing | Does the type implement the required trait? |
The compiler’s explanation is more reliable than applying a memorized fix blindly. rustc --explain CODE gives detail. After changing one ownership decision, re-check before responding to every secondary diagnostic.
22.5 Debugging data and runtime behavior
dbg!(&value) can print an expression and developer representation to stderr while borrowing the value. Remove or control diagnostics before shipping if they may expose data. Use a debugger appropriate to your target and toolchain when inspecting runtime state.
When a FileMaker call fails, first determine whether the service is listening on the host executing the script. Next inspect the captured FileMaker error and controlled response body. Then isolate the same request with the CLI or a local HTTP client. This separates calculation failures from connection and script-context failures.
23. Common translation mistakes
| Mistake | Consequence | Better approach |
|---|---|---|
Translate every field to String | Validation and arithmetic move into scattered parsing code | Use suitable typed fields after the boundary |
Treat struct as a live record | In-memory edits are mistaken for database writes | Keep persistence explicit |
Use = as equality | Assignment or a compiler type error | Use == |
Use & as text concatenation | Borrow/bitwise syntax means something else | Use format! or append methods |
| Apply truthiness to integers | Rust rejects the condition | Write an explicit Boolean comparison |
| Keep FileMaker repetition numbers as vector indexes | Off-by-one errors | Convert and validate once at the boundary |
| Drop blank repetition slots | Positional data shifts | Preserve None/null or explicit indexes |
| Use vectors for sparse repetition keys | Wasted storage or incorrect meaning | Use a keyed map |
Use zip without length checks | Extra values silently go unprocessed | Validate lengths or use a paired struct |
Expect .len() to count displayed characters | Wrong Unicode limits or slicing | Define the counting unit |
Split all FileMaker lists with .lines() | Bare carriage-return boundaries may be missed | Define the delimiter or use JSON arrays |
| Use floating point for exact invoice cents | Unexpected rounding | Choose a scale and explicit money model |
Use as for input validation | Narrowing can alter values | Use TryFrom and range checks |
| Add clones to every borrow error | Expensive snapshots and unclear ownership | Read the function’s access contract |
Use unwrap on external input | Request data can trigger a panic | Return and handle Result |
| Assume a Rust thread is PSoS | No FileMaker session or privileges exist | Use an actual integration/API boundary |
| Use client localhost from a server worker | Request targets the wrong machine | Resolve execution location explicitly |
| Assume Rust provides authorization | Valid code can process unauthorized data | Enforce the application access policy |
| Assume a lockfile guarantees a safe package | Reproducibility is confused with trust | Review package origin and update policy |
| Treat an HTTP timeout as proof nothing happened | Retried writes can duplicate side effects | Use a durable idempotency design for writes |
24. Exercises with worked answers
Exercise 1: Fix the quantity condition
Why is this rejected?
let quantity = 3;
if quantity {
println!("Ready");
}
Answer: The condition is an integer. Use if quantity > 0 { ... } if positive quantity is the business rule. Do not merely compare with zero if negative quantities would require a distinct outcome.
Exercise 2: Preserve twelve month slots
Model January = €0.00, February = not entered, March = €12.50, with the remaining months not entered.
Answer:
let mut months: [Option<u64>; 12] = [None; 12];
months[0] = Some(0);
months[2] = Some(1_250);
assert_eq!(months.len(), 12);
assert_eq!(months[1], None);
Zero and missing are distinct; March stays in its third position.
Exercise 3: Read an untrusted repetition number
Write a function that converts a positive FileMaker repetition number into a safe lookup.
Answer: Use the generic fm_repetition function in chapter 9. checked_sub(1)? handles zero; .get(index) handles indexes beyond the sequence. For signed external input, first reject negative values or use a checked conversion to usize.
Exercise 4: Repair a moved value
fn print_quote(id: String) {
println!("{id}");
}
let id = String::from("Q-1001");
print_quote(id);
// Need to use id again here.
Answer: If the function only reads the ID, change the signature to fn print_quote(id: &str) and call print_quote(&id). Clone only if independent ownership is required.
Exercise 5: Predict the quote total
One line has quantity 1 and unit price 3 cents, discount is 50%, and tax is 50%. Use the project’s rule.
Answer: Subtotal = 3. Discount = 2 after half-up rounding. Net = 1. Tax = 1 after half-up rounding. Total = 2 cents. Calculating both rates on the original subtotal would implement another policy.
Exercise 6: Explain a rejected request
{
"schema_version": 1,
"quote_id": "Q-1001",
"currency": "EUR",
"discount_bps": 1000,
"tax_bps": 2400,
"lines": [{"quantity": "2", "unit_cents": 1250}]
}
Answer: Quantity is a JSON string. It must be an integer. In FileMaker, use the JSON numeric type when building this property, after validating the source value.
Exercise 7: Locate the service
Rust is listening on your Windows workstation. A PSoS worker on Ubuntu calls http://127.0.0.1:8787/v1/quote. Why does it fail?
Answer: The worker is contacting Ubuntu’s loopback interface. Run the service on that host or configure a reachable HTTPS service. Changing Rust ownership code cannot correct a host-location mistake.
Exercise 8: Add a new currency
Is removing the EUR check sufficient to support any currency?
Answer: No. Define supported currency identifiers, minor-unit scale, formatting expectations, and rounding rules. Validate and test each supported model. Avoid pretending that every amount is “cents” across all currencies.
Exercise 9: Model approval
The FileMaker solution uses isDraft, isApproved, and isRejected checkboxes that can contradict one another. What does an enum improve?
Answer: A QuoteState value chooses one alternative and can carry state-specific data. Transition functions still need to validate permissions and allowed transitions. An enum does not establish those rules by itself.
Exercise 10: Find the real next step
Choose one existing FileMaker calculation that is difficult to test. Document its explicit inputs, outputs, units, absent-value rules, and error cases. Implement the pure rule in Rust, validate it against known fixtures, and only then add a FileMaker adapter.
Worked approach: A quote calculation is suitable because inputs are a bounded array of lines and rates. A script that prints a layout, changes windows, and emails a PDF has several unrelated side effects; isolate one deterministic transformation before attempting to move the whole workflow.
25. Reference tables and further reading
25.1 Syntax reference
| Rust | Read it as |
|---|---|
let x = value; | Bind a value |
let mut x = value; | Bind a value that may be reassigned or mutably accessed |
const LIMIT: usize = 100; | Define a typed constant |
fn f(x: T) -> U | Function taking T and returning U |
&value | Borrow shared access |
&mut value | Borrow exclusive mutable access |
*reference | Access the referent, subject to ownership/type rules |
Type::function() | Call an associated function or a namespaced function |
value.method() | Call a method |
Option<T> | A value may be present or absent |
Result<T, E> | An operation produces success or error |
operation()? | Propagate a compatible error/absence |
if let Some(x) = value | Act on a matching present value |
match value { ... } | Select a pattern arm exhaustively |
for x in sequence | Iterate over a sequence |
0..n | Exclude the end |
1..=n | Include the end |
Vec<T> | Owned growable sequence |
&[T] | Borrowed sequence |
#[derive(...)] | Request generated trait implementations |
#[cfg(...)] | Conditionally compile an item |
pub | Expose an item subject to its enclosing visibility |
async fn | Define a function producing a future |
.await | Await a future inside an async context |
25.2 Choose the smallest sufficient type
| Requirement | Start with |
|---|---|
| Read text | &str |
| Store independently owned text | String |
| Read rows | &[Row] |
| Build or own ordered rows | Vec<Row> |
| Preserve twelve fixed slots | [Option<T>; 12] when absence is meaningful |
| Look up sparse keys | HashMap<Key, Value> |
| Preserve key order | BTreeMap<Key, Value> |
| Distinguish absent from empty | Option<T> plus explicit empty-value rules |
| Represent one of several states | enum |
| Prevent mixing ID types | Newtype structs |
| Report a recoverable failure | Result<Success, Error> |
| Share immutable owned data across threads | Arc<T> when T meets the required bounds |
| Share mutable in-process state | A deliberate synchronized design, often a suitable lock or channel |
25.3 Suggested learning order
- Run the CLI and inspect the request/response.
- Work through types, operators, conditions, and loops.
- Translate one repeating-field model, preserving empty slots.
- Learn borrowing with small
Stringexamples. - Read the core quote function and its tests.
- Run the HTTP service and the FileMaker reconstruction guide.
- Introduce traits, async, or native FFI only when the component actually requires them.
25.4 Official references
These are primary documentation sources, checked while preparing the tutorial. The chapter links above point to the relevant language/API sections rather than relying on third-party summaries.
| Resource | Use |
|---|---|
| The Rust Programming Language | Language fundamentals and examples |
| The Rust Reference | Precise language structures and semantics |
| Standard library | Collection, string, numeric, I/O, and synchronization APIs |
| The Cargo Book | Packages, builds, dependencies, lockfiles, features |
| The Rust Edition Guide | Edition selection and compatibility |
| Official installation | Supported toolchain installation |
| Serde derive | Typed serialization and deserialization |
| Axum 0.8 documentation | HTTP framework used in the companion project |
| Claris FileMaker Pro Help | Script and calculation behavior |
| Insert from URL | Native FileMaker HTTP integration |
| Supported cURL options | FileMaker-specific variable-backed request behavior |
| JSON functions | Explicit JSON types and response processing |
| FileMaker Data API guide | Authenticated access to hosted FileMaker records |
Appendix A. Main project source
The following listings are copied from the companion source project. Tests, the lockfile, and the completed validation record are included in the downloadable project.
Cargo.toml
[package]
name = "rust-filemaker-lab"
version = "0.1.0"
edition = "2024"
default-run = "quote-cli"
[features]
default = []
http = ["dep:axum", "dep:tokio"]
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
axum = { version = "0.8", optional = true }
tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "signal"], optional = true }
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
[[bin]]
name = "quote-cli"
path = "src/bin/quote-cli.rs"
[[bin]]
name = "quote-http"
path = "src/bin/quote-http.rs"
required-features = ["http"]
src/lib.rs
//! A deterministic quote calculator. No database or FileMaker session is accessed.
use serde::{Deserialize, Serialize};
pub const MAX_REQUEST_BYTES: usize = 256 * 1024;
pub const MAX_LINES: usize = 1_000;
/// Keeps output integers exactly representable in common binary64 JSON clients.
pub const MAX_SAFE_CENTS: u64 = 9_007_199_254_740_991;
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct QuoteRequest {
pub schema_version: u16,
pub quote_id: String,
pub currency: String,
pub discount_bps: u32,
pub tax_bps: u32,
pub lines: Vec<QuoteLine>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct QuoteLine {
pub quantity: u32,
pub unit_cents: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct QuoteTotals {
pub quote_id: String,
pub currency: String,
pub subtotal_cents: u64,
pub discount_cents: u64,
pub net_cents: u64,
pub tax_cents: u64,
pub total_cents: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct AppError {
pub code: String,
pub message: String,
}
impl AppError {
pub fn new(code: &str, message: impl Into<String>) -> Self {
Self {
code: code.into(),
message: message.into(),
}
}
}
impl std::fmt::Display for AppError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.code, self.message)
}
}
impl std::error::Error for AppError {}
#[derive(Debug, Serialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum ApiResponse {
Ok { data: QuoteTotals },
Error { error: AppError },
}
impl From<Result<QuoteTotals, AppError>> for ApiResponse {
fn from(result: Result<QuoteTotals, AppError>) -> Self {
match result {
Ok(data) => Self::Ok { data },
Err(error) => Self::Error { error },
}
}
}
fn amount_error() -> AppError {
AppError::new(
"amount_out_of_range",
"Amount exceeds the supported integer range",
)
}
fn supported_amount(amount: u64) -> Result<u64, AppError> {
if amount > MAX_SAFE_CENTS {
Err(amount_error())
} else {
Ok(amount)
}
}
/// Round nonnegative basis-point calculations to the nearest cent; ties round up.
fn rounded_bps(amount: u64, bps: u32) -> Result<u64, AppError> {
let rounded = (u128::from(amount) * u128::from(bps) + 5_000) / 10_000;
let value = u64::try_from(rounded).map_err(|_| amount_error())?;
supported_amount(value)
}
pub fn calculate_quote(request: &QuoteRequest) -> Result<QuoteTotals, AppError> {
if request.schema_version != 1 {
return Err(AppError::new(
"unsupported_version",
"schema_version must be 1",
));
}
if request.quote_id.trim().is_empty() || request.quote_id.len() > 128 {
return Err(AppError::new(
"invalid_quote_id",
"quote_id must be nonblank and at most 128 UTF-8 bytes",
));
}
if request.currency != "EUR" {
return Err(AppError::new(
"unsupported_currency",
"This teaching service supports EUR only",
));
}
if request.discount_bps > 10_000 || request.tax_bps > 10_000 {
return Err(AppError::new(
"invalid_rate",
"Rates must be between 0 and 10000 basis points",
));
}
if request.lines.is_empty() || request.lines.len() > MAX_LINES {
return Err(AppError::new(
"invalid_line_count",
"Supply between 1 and 1000 lines",
));
}
let mut subtotal = 0_u64;
for (index, line) in request.lines.iter().enumerate() {
if line.quantity == 0 || line.quantity > 1_000_000 {
return Err(AppError::new(
"invalid_quantity",
format!("Line {}: quantity must be 1..=1000000", index + 1),
));
}
supported_amount(line.unit_cents)?;
let line_total = u64::from(line.quantity)
.checked_mul(line.unit_cents)
.ok_or_else(amount_error)?;
subtotal = supported_amount(subtotal.checked_add(line_total).ok_or_else(amount_error)?)?;
}
let discount = rounded_bps(subtotal, request.discount_bps)?;
let net = subtotal.checked_sub(discount).ok_or_else(amount_error)?;
let tax = rounded_bps(net, request.tax_bps)?;
let total = supported_amount(net.checked_add(tax).ok_or_else(amount_error)?)?;
Ok(QuoteTotals {
quote_id: request.quote_id.clone(),
currency: request.currency.clone(),
subtotal_cents: subtotal,
discount_cents: discount,
net_cents: net,
tax_cents: tax,
total_cents: total,
})
}
pub fn process_json(input: &[u8]) -> ApiResponse {
if input.len() > MAX_REQUEST_BYTES {
return ApiResponse::Error {
error: AppError::new("payload_too_large", "Request exceeds 256 KiB"),
};
}
match serde_json::from_slice::<QuoteRequest>(input) {
Ok(request) => calculate_quote(&request).into(),
Err(_) => ApiResponse::Error {
error: AppError::new(
"invalid_json",
"JSON syntax or request field types do not match the contract",
),
},
}
}
#[cfg(feature = "http")]
pub mod http;
src/bin/quote-cli.rs
use rust_filemaker_lab::{ApiResponse, MAX_REQUEST_BYTES, process_json};
use std::io::{self, Read, Write};
use std::process::ExitCode;
fn run() -> Result<bool, Box<dyn std::error::Error>> {
let mut input = Vec::new();
io::stdin()
.lock()
.take((MAX_REQUEST_BYTES + 1) as u64)
.read_to_end(&mut input)?;
let response = process_json(&input);
let successful = matches!(response, ApiResponse::Ok { .. });
let mut output = io::stdout().lock();
serde_json::to_writer(&mut output, &response)?;
writeln!(output)?;
Ok(successful)
}
fn main() -> ExitCode {
match run() {
Ok(true) => ExitCode::SUCCESS,
Ok(false) => ExitCode::from(2),
Err(error) => {
eprintln!("I/O or serialization failure: {error}");
ExitCode::from(1)
}
}
}
src/http.rs
use crate::{ApiResponse, AppError, MAX_REQUEST_BYTES, QuoteRequest, calculate_quote};
use axum::{
Json, Router,
extract::{DefaultBodyLimit, State, rejection::JsonRejection},
http::{HeaderMap, StatusCode},
routing::{get, post},
};
use std::sync::Arc;
fn failure(status: StatusCode, code: &str, message: &str) -> (StatusCode, Json<ApiResponse>) {
(
status,
Json(ApiResponse::Error {
error: AppError::new(code, message),
}),
)
}
async fn quote(
State(token): State<Arc<str>>,
headers: HeaderMap,
payload: Result<Json<QuoteRequest>, JsonRejection>,
) -> (StatusCode, Json<ApiResponse>) {
let supplied = headers
.get("x-fm-token")
.and_then(|value| value.to_str().ok());
if supplied != Some(token.as_ref()) {
return failure(
StatusCode::UNAUTHORIZED,
"unauthorized",
"Missing or invalid service token",
);
}
let request = match payload {
Ok(Json(request)) => request,
Err(rejection) => {
let status = rejection.status();
let code = if status == StatusCode::PAYLOAD_TOO_LARGE {
"payload_too_large"
} else {
"invalid_json"
};
return failure(
status,
code,
"Request body does not match the JSON contract or body limit",
);
}
};
match calculate_quote(&request) {
Ok(data) => (StatusCode::OK, Json(ApiResponse::Ok { data })),
Err(error) => (
StatusCode::UNPROCESSABLE_ENTITY,
Json(ApiResponse::Error { error }),
),
}
}
pub fn router(token: String) -> Result<Router, AppError> {
if token.len() < 32 || !token.bytes().all(|byte| byte.is_ascii_alphanumeric()) {
return Err(AppError::new(
"invalid_configuration",
"APP_TOKEN must contain at least 32 ASCII letters or digits",
));
}
Ok(Router::new()
.route("/health", get(|| async { "ok" }))
.route("/v1/quote", post(quote))
.layer(DefaultBodyLimit::max(MAX_REQUEST_BYTES))
.with_state(Arc::<str>::from(token)))
}
src/bin/quote-http.rs
use rust_filemaker_lab::http::router;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let token = std::env::var("APP_TOKEN")?;
let app = router(token)?;
let listener = tokio::net::TcpListener::bind("127.0.0.1:8787").await?;
eprintln!("Listening on http://127.0.0.1:8787");
axum::serve(listener, app)
.with_graceful_shutdown(async {
let _ = tokio::signal::ctrl_c().await;
})
.await?;
Ok(())
}