lotsoftools

Understanding Rust Error E0791

Introduction

Rust Error E0791 occurs when static variables within an external block have an invalid type. This error is related to the #[linkage] attribute, which is used to adjust the linkage properties of definitions in external linkage.

Invalid Types and Correct Usage

To fix Rust Error E0791, the static variables must be of one of the following types: 1. *mut T or *const T, where T may be any type. 2. An enumerator type with no #[repr] attribute and with two variants: - One variant with no fields. - Another variant with a single field of one of these non-nullable types: - Reference type - Function pointer type The variants can appear in any order.

Invalid Example

The following declaration is invalid:

#![allow(unused)]
#![feature(linkage)]

fn main() {
extern "C" {
    #[linkage = "extern_weak"]
    static foo: i8;
}
}

Valid Examples

These declarations are valid:


#![allow(unused)]
#![feature(linkage)]

fn main() {
extern "C" {
    #[linkage = "extern_weak"]
    static foo: Option<unsafe extern "C" fn()>;

    #[linkage = "extern_weak"]
    static bar: Option<&'static i8>;

    #[linkage = "extern_weak"]
    static baz: *mut i8;
}
}

Explanation

In the invalid example, using `static foo: i8` is not allowed, as `i8` is not one of the accepted types for static variables with the #[linkage] attribute within an external block. In the valid examples, `static foo: Option<unsafe extern "C" fn()>`, `static bar: Option<&'static i8>`, and `static baz: *mut i8` meet the requirements of acceptable types.