This guide outlines generic best practices, style conventions, and API design rules for writing Rust code in Fuchsia. It incorporates the official Fuchsia Rust Rubric (from docs/development/api/rust.md). For driver-specific practices, refer to the rust_driver_best_practices skill.
CamelCase for types, snake_case for functions and variables, and SCREAMING_SNAKE_CASE for constants. See C-CASE.get_: Do not use the get_ prefix for getter methods. Use direct field names (e.g., rect.width() instead of rect.get_width()). See C-GETTER.as_: Cheap, reference-to-reference conversion (e.g., as_bytes()).to_: Expensive, reference-to-value/owned conversion (e.g., to_str()).into_: Consuming value-to-value conversion (e.g., into_vec()).iter, iter_mut, into_iter. Iterator type names should match the methods that produce them (e.g., Iter, IterMut, IntoIter). See C-ITER and C-ITER-TY.new_connection and open_connection, rather than mixing prefixes and suffixes). See C-WORD-ORDER.use statements must be grouped together at the top of the file. Do not place use statements inline within functions or modules. This makes file dependencies clear and easy to find.use statements to import symbols so that you can avoid long namespaced structs or methods in the code. This improves readability.allow_unused: Do not leave #[allow(unused)] or #[allow(dead_code)] in the final implementation. If a field is intentionally unused but must be held by a struct (like an async scope to keep it alive), prefix its name with an underscore (e.g., _scope).impl block if the type is important to the function's purpose (e.g., constructors returning Self or a Result/Option of Self).Thing::does_what() over a free function named thing_does_what()).mod), not the type itself. Free functions inside the same module can access private fields of a struct just as easily as associated functions.const definitions at the top of the file or module for loop counts, timeout limits, array sizes, and configuration values.Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Display, and Default. See C-COMMON-TRAITS.From, AsRef, and AsMut rather than custom methods where possible. Implementing From<A> for B automatically gives you Into<B> for A. See C-CONV-TRAITS.FromIterator and Extend to interact naturally with standard Rust iterators and .collect(). See C-COLLECT.Serialize and Deserialize traits. See C-SERDE.Send and Sync where possible. Ensure your design doesn't inadvertently block these traits unless thread unsafety is intended. See C-SEND-SYNC.std::error::Error. Avoid returning raw strings or generic error types unless prototyping. See C-GOOD-ERR.Hex, Octal, and Binary. See C-NUM-FMT.R: Read and W: Write by value, not by reference, to allow callers to pass owned readers/writers or standard wrappers. See C-RW-VALUE.self, &self, or &mut self. See C-METHOD.Add for a custom complex number type). See C-OVERLOAD.Deref & DerefMut: Implement Deref and DerefMut ONLY for smart pointers. Do not use them for inheritance or code reuse. See C-DEREF.new or with_...). See C-CTOR.Cow rather than cloning internally). See C-CALLER-CONTROL.impl AsRef<str> instead of &str if appropriate). See C-GENERIC.struct UserId(u64) rather than a plain u64). See C-NEWTYPE.Option types. See C-CUSTOM-TYPE.bitflags crate to represent a set of flags, not enums or raw integers. See C-BITFLAG.impl blocks instead. See C-STRUCT-BOUNDS.spawn vs spawn_local:scope.spawn() as the default when the task implements Send.scope.spawn_local() when the task does not implement Send (e.g., it holds non-thread-safe types like Rc or RefCell).fuchsia_async::Task::spawn(...).detach();. Detaching tasks is considered bad style and can lead to resource leaks or silent task failures. Use scope.spawn(...); instead.fuchsia_sync::Mutex over std::sync::Mutex.pub, pub(crate)). See C-MACRO-VIS.Crate-Level Docs: Crate-level documentation must be thorough and include examples of how to use the crate. See C-CRATE-DOC.
Item Examples: All public items should have a rustdoc example illustrating their usage. See C-EXAMPLE.
[!NOTE] This guideline is not strictly enforced for targets building on Fuchsia until doctests are supported on Fuchsia targets.
Ergonomic Examples: Examples should use the ? operator, not try!, and not call unwrap or expect. See C-QUESTION-MARK.
Function Failure and Safety: Function docs must clearly document:
Err.unsafe functions). See C-FAILURE.Prose Hyperlinks: Include hyperlinks to relevant types, methods, and concepts in rustdoc prose. See C-LINK.
Hide Implementation Details: Rustdoc should not show unhelpful internal implementation details. See C-HIDDEN.
Error Handling: Avoid unwrap() and expect() which can panic the process. Use ok_or_else() or handle errors explicitly. If an error is truly unrecoverable, provide a context string explaining why it is safe to panic.
Arithmetic: Always use checked math operations (e.g., checked_add(), checked_mul()) on external or untrusted input to prevent overflows.
Fuchsia Unsafe Guidelines:
[!IMPORTANT] Every
unsafeblock must have an accompanying justification. Safety justifications should begin with// SAFETY:and explain why the unsafe block is sound.
// SAFETY: <why this unsafe operation is sound>// Safety:, // [SAFETY], or lazy placeholders like // SAFETY: Trust me.Do:
// SAFETY: The `bytes` returned from our string builder are guaranteed to be // valid UTF-8. We used to call `from_utf8`, but this caused performance issues // with large inputs. let s = unsafe { String::from_utf8_unchecked(bytes) };
Don't:
// SAFETY: We shouldn't have to validate `bytes`, and the safe version is slow. let s = unsafe { String::from_utf8_unchecked(bytes) };
Unsafe Traits & Impls:
// SAFETY: comment pattern.Always use unsafe Blocks in unsafe Functions:
unsafe functions are not considered unsafe contexts in Fuchsia. Unsafe operations must always be located inside an explicit unsafe block, even if they are in an unsafe function body.Do:
unsafe fn clear_slice(ptr: *mut i32, len: usize) { assert!(len.checked_mul(mem::size_of::<i32>()).unwrap() < isize::MAX); // SAFETY: // - The caller has guaranteed that `ptr` points to `len` consecutive, valid // i32s and that the data behind `ptr` is not simultaneously accessed. // - We asserted that the total size of the slice is less than isize::MAX. let slice = unsafe { slice::from_raw_parts_mut(ptr, len) }; for x in slice.iter_mut() { *x = 0; } }
Drop implementations) should never fail or panic. See C-DTOR-FAIL.Debug. See C-DEBUG.Debug representation should never be empty. See C-DEBUG-NONEMPTY.#[fuchsia::test] instead of #[test]. It natively supports async tests and logging out of the box.assert_matches crate for pattern assertions and pretty_assertions for colored diffs on failure.with_unit_tests = true to your rustc_binary or rustc_library templates to generate test targets.edition = "2024" for new BUILD.gn Rust targets.fuchsia_zircon crate. Use the standard zx bindings or relevant crates.zx::AsHandleRef to call methods on handles. It is no longer needed.lazy_static! macro. Use std::sync::LazyLock from the standard library instead.Upon finishing authoring a change to Rust code, you MUST use this skill to review the change. Verify that:
use statements are grouped at the top of the file.#[allow(unused)] or #[allow(dead_code)] attributes remain in the final code.spawn vs spawn_local is correctly chosen based on Send requirements.fuchsia_sync::Mutex is preferred if a mutex is strictly necessary.#[fuchsia::test] is used for tests.unwrap() and expect() are avoided where possible.unsafe block has a // SAFETY: comment that details exactly why it is sound and necessary.unsafe functions are wrapped in an explicit unsafe block.Debug and getter methods avoid get_.