rust-best-practicesот apollographql

Idiomatic Rust coding standards based on Apollo GraphQL's best practices handbook. Covers nine core areas: coding styles and idioms, clippy linting, performance optimization, error handling, testing patterns, generics and dispatch, type state pattern, documentation, and pointer safety Emphasizes borrowing over cloning, Result-based error handling with thiserror/anyhow, and performance profiling with release builds Includes quick reference guidance on ownership patterns, panic avoidance,...

npx skills add https://github.com/apollographql/skills --skill rust-best-practices

Rust Best Practices

Apply these guidelines when writing or reviewing Rust code. Based on Apollo GraphQL's Rust Best Practices Handbook.

Best Practices Reference

Before reviewing, familiarize yourself with Apollo's Rust best practices. Read ALL relevant chapters in the same turn in parallel. Reference these files when providing feedback:

Quick Reference

Borrowing & Ownership

  • Prefer &T over .clone() unless ownership transfer is required
  • Use &str over String, &[T] over Vec<T> in function parameters
  • Small Copy types (≤24 bytes) can be passed by value
  • Use Cow<'_, T> when ownership is ambiguous

Error Handling

  • Return Result<T, E> for fallible operations; avoid panic! in production
  • Never use unwrap()/expect() outside tests
  • Use thiserror for library errors, anyhow for binaries only
  • Prefer ? operator over match chains for error propagation

Performance

  • Always benchmark with --release flag
  • Run cargo clippy -- -D clippy::perf for performance hints
  • Avoid cloning in loops; use .iter() instead of .into_iter() for Copy types
  • Prefer iterators over manual loops; avoid intermediate .collect() calls

Linting

Run regularly: cargo clippy --all-targets --all-features --locked -- -D warnings

Key lints to watch:

  • redundant_clone - unnecessary cloning
  • large_enum_variant - oversized variants (consider boxing)
  • needless_collect - premature collection

Use #[expect(clippy::lint)] over #[allow(...)] with justification comment.

Testing

  • Name tests descriptively: process_should_return_error_when_input_empty()
  • One assertion per test when possible
  • Use doc tests (///) for public API examples
  • Consider cargo insta for snapshot testing generated output

Generics & Dispatch

  • Prefer generics (static dispatch) for performance-critical code
  • Use dyn Trait only when heterogeneous collections are needed
  • Box at API boundaries, not internally

Type State Pattern

Encode valid states in the type system to catch invalid operations at compile time:

struct Connection<State> { /* ... */ _state: PhantomData<State> }
struct Disconnected;
struct Connected;

impl Connection<Connected> {
    fn send(&self, data: &[u8]) { /* only connected can send */ }
}

Documentation

  • // comments explain why (safety, workarounds, design rationale)
  • /// doc comments explain what and how for public APIs
  • Every TODO needs a linked issue: // TODO(#42): ...
  • Enable #![deny(missing_docs)] for libraries

Больше skills от apollographql

apollo-client
by apollographql
Apollo Client is a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL. Version 4.x brings improved caching, better TypeScript support, and React 19 compatibility.
apollo-client
by apollographql
Comprehensive guide for building React applications with Apollo Client 4.x, covering queries, mutations, caching, and state management. Supports multiple React frameworks and setups: client-side apps (Vite, CRA), Next.js App Router with React Server Components, React Router 7 with streaming SSR, and TanStack Start Includes hooks for queries ( useQuery , useLazyQuery ), mutations ( useMutation ), and Suspense-based patterns ( useSuspenseQuery , useBackgroundQuery ) for modern React 18+ and 19...
apollo-connectors
by apollographql
Integrate REST APIs into GraphQL supergraphs using @source and @connect directives. Provides a structured 5-step process: research API structure, implement schema with directives, validate via rover supergraph compose , execute connectors, and test coverage Supports request configuration including headers, body payloads, batching for N+1 patterns, and environment variable injection via $env Handles response mapping with field selection, aliasing, sub-selections for nested data, and entity...
apollo-federation
by apollographql
Apollo Federation enables composing multiple GraphQL APIs (subgraphs) into a unified supergraph.
apollo-ios
by apollographql
Apollo iOS is a strongly-typed GraphQL client for Apple platforms. It generates Swift types from your GraphQL operations and schema, and ships an async/await client, a normalized cache (in-memory or SQLite-backed), a pluggable interceptor-based HTTP transport that handles queries, mutations, and multipart subscriptions, and an optional WebSocket transport ( graphql-transport-ws ) that can carry any operation type.
apollo-kotlin
by apollographql
Apollo Kotlin is a strongly typed GraphQL client that generates Kotlin models from your GraphQL operations and schema, that can be used in Android, JVM, and Kotlin Multiplatform projects.
apollo-mcp-server
by apollographql
Connect AI agents to GraphQL APIs through the Model Context Protocol with built-in introspection and operation tools. Exposes GraphQL operations as MCP tools; supports three operation sources: local files, GraphOS Studio collections, and persisted query manifests Provides four introspection tools (introspect, search, validate, execute) for schema exploration and ad-hoc query testing; minification mode reduces token usage with compact notation Configurable authentication via static headers,...
apollo-router
by apollographql
Apollo Router is a high-performance graph router written in Rust for running Apollo Federation 2 supergraphs. It sits in front of your subgraphs and handles query planning, execution, and response composition.

NotebookLM Web Importer

Импортируйте веб-страницы и видео YouTube в NotebookLM одним кликом. Более 200 000 пользователей доверяют нам.

Установить расширение Chrome