Skip to content

Check casting function item to usize #5906

Closed
@tesuji

Description

@tesuji

What it does

Check a mistaken casting function item to usize or all other integer primitive types.

Categories (optional)

  • Kind: correctness or pedantic

What is the advantage of the recommended code over the original code

  • It is a mistake to cast a function item to usize instead of getting function result.
    This could be unnotice for a long time.
  • If you want to get pointer address of a function, explicitly cast it to function pointer and usize.
  • Explicit is better than implicit.

The bug appeared in real code: rust-lang/rustup@5d9d980
I was author of the bug :) .

Drawbacks

It is verbose and somewhat redundant.

Example

use std::mem::size_of;

extern "C" {
    fn foo(len: usize);
}

unsafe {
    foo(size_of::<usize> as usize);
}

Could be written as:

unsafe {
    foo(size_of::<usize>());
    // or
    foo(size_of::<usize> as fn() -> usize as usize);
    // or
    foo(size_of::<usize> as *const () as usize);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lintsgood first issueThese issues are a good way to get started with Clippy

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions