rust-lang / rust-lang/rust-clippy

Suggest `.cast()` instead of `as` for pointer casts

Open
#8,017 3 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

What it does

Suggests using the more-scoped cast methods
https://doc.rust-lang.org/std/primitive.pointer.html#method.cast
https://doc.rust-lang.org/std/primitive.pointer.html#method.cast-1
for pointer casting instead of the more-general as.

Categories (optional)
  • Kind: style

(One could argue that this is more pedantic, as that's what https://rust-lang.github.io/rust-clippy/master/index.html#cast_lossless is. But I think that pointer casts are generally around unsafe code, so the pedantry is more generally appropriate.)

This helps avoid mistakes where the as cast is accidentally converting between *const _ and *mut _, for example. For pointers it's often tempting to slap on as _ to make something work, but that's a very broad conversion.

(This is not applicable for *const T <-> *mut T casts, which this lint should not warn about.)

Drawbacks

None.

Example

From https://users.rust-lang.org/t/converting-between-unsized-transparent-types-safely-in-place/67680/19?u=scottmcm

impl<T> From<OrderedVecSet<T>> for Rc<OrderedVecSetUnsized<T>>
where
    T: Ord,
{
    fn from(set: OrderedVecSet<T>) -> Self {
        let rc: Rc<[T]> = set.0.into();
        unsafe { Rc::from_raw(Rc::into_raw(rc) as _) }
    }
}

Could be written as:

impl<T> From<OrderedVecSet<T>> for Rc<OrderedVecSetUnsized<T>>
where
    T: Ord,
{
    fn from(set: OrderedVecSet<T>) -> Self {
        let rc: Rc<[T]> = set.0.into();
        unsafe { Rc::from_raw(Rc::into_raw(rc).cast()) }
    }
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading the Rust pointer::cast documentation linked in the issue and the example conversions. Identify the Clippy lint entry point and its tests for style lints, then verify the warning applies to pointer casts using as while excluding *const T to *mut T and the reverse. Done means the lint suggests .cast() with coverage for the shown cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.