Skip to content

Diagnostics in FFI use recommend users to cast to i/u8 instead of the appropriate c_char #89325

Open
@skade

Description

@skade

Note: related to the lint described in #79089

Given the following code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=e4aed9f0b25f39886e30db193cf508e2

use libc::c_char;

fn fun(c: c_char) {
    
}

fn main() {
    let x: u8 = 3;
    
    fun(x)
}

The current output is:

Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
  --> src/main.rs:10:9
   |
10 |     fun(x)
   |         ^ expected `i8`, found `u8`
   |
help: you can convert a `u8` to an `i8` and panic if the converted value doesn't fit
   |
10 |     fun(x.try_into().unwrap())
   |         ^^^^^^^^^^^^^^^^^^^^^

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground` due to previous error

Ideally the output should look like:

   Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
  --> src/main.rs:10:9
   |
10 |     fun(x)
   |         ^ expected `i8`, found `u8`
   |
help: you can convert a `u8` to an `c_char` and panic if the converted value doesn't fit
   |
10 |     fun(x.try_into().unwrap())
   |         ^^^^^^^^^^^^^^^^^^^^^

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground` due to previous error

c_char is different on platforms, it may be u8 or i8. The correct cast here in FFI use is towards a c_char, keeping casts correct in all situations. There's also an argument to be made that i8 -> c_char should be using an as cast.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions