rust-lang / rust-lang/rust-clippy
Suggest using `as_mut()` and `as_ref()` instead of `(*ptr.as_ptr()).field` in unsafe Rust.
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
What it does
It suggests the developer to write cleaner code when using unsafe Rust. Rust has been critisized for (*ptr.as_ptr()).field syntax for accessing field in from a *mut T in unsafe Rust. Frankly, it looks horrible and many people are not aware the helper methods .as_mut() and .as_ref() on raw pointers.
Advantage
This will improve the developer experience when reading and writing unsafe rust code using raw pointers.
Drawbacks
Nothing that I can think of but I'd like to know if you find any!
Example
struct Node {
elem: i32,
next: Option<NonNull<Node>>
};
let node: NonNull<Node> = NonNull::new_unchecked(Node { elem: 10, next: None });
// Using longer syntax on right for demonstration
(*node.as_ptr()).elem = (*node.as_ptr()).elem * 2;
Could be written as:
// ...omitted
// notice `mut` here
let mut node = NonNull::new_unchecked(Node { elem: 10, next: None });
// Mutable and immutable access seperately
node.as_mut().elem = node.as_ref().elem * 2;
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
No implementation file or test is named; start by reading the examples in this issue and the 17-comment discussion to identify the intended lint scope and diagnostic behavior. Done means an agreed, tested Clippy lint for the unsafe raw-pointer field-access pattern and its suggested as_mut()/as_ref() form.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100