expression
REST: deterministic sorting with tie-breakers
Paginated results need a total ordering. Sort by the requested field and use a unique secondary key when primary values tie. This local ascending example makes the tie-break rule explicit. A database-backed API must use the same order in every page and cursor comparison. Standalone synthetic example. Expected stdout (not executed): [2, 1, 3] Common mistake: Sorting only by a non-unique field and assuming tied records have a consistent order across requests.
Formal Syntax & Structure
rust syntaxrust
sort_by_key(|item| (price, id))Working Example
Example Snippetrust
use axum::{Router, Json, body::{Body, to_bytes}, http::{Request, StatusCode}};use serde::{Deserialize, Serialize};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() { let mut items = [(3, 10), (1, 10), (2, 5)]; // (id, price) items.sort_by_key(|&(id, price)| (price, id)); let ids: Vec<_> = items.iter().map(|&(id, _)| id).collect(); println!("{ids:?}");}