expression
REST: offset pagination with next offset
Offset pagination skips a number of records and returns a bounded slice. This static sorted collection can calculate whether another page exists without an extra query. Use checked arithmetic and avoid assuming offsets stay stable when records are inserted or removed. Real database queries need explicit ordering. Standalone synthetic example. Expected stdout (not executed): [30, 40] Some(4) Common mistake: Assuming an offset always refers to the same records in a changing collection.
Formal Syntax & Structure
rust syntaxrust
items.iter().skip(offset).take(limit)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 items = [10, 20, 30, 40, 50]; let offset = 2usize; let limit = 2usize; let page: Vec<_> = items.iter().copied().skip(offset).take(limit).collect(); let next = offset.checked_add(page.len()).filter(|&n| n < items.len()); println!("{page:?}"); println!("{next:?}");}