Implement basic operations for built-in types without using libcore

When I write simple code for bare metal without using libcore, I get the following error:

Error: binary operation != Cannot be applied to type u32 [E0369]

Direct implementation faces the problem of chicken and eggs:

 #![crate_type = "lib"] #![feature(no_std, no_core, lang_items)] #![no_std] #![no_core] #[lang = "sized"] pub trait Sized {} #[lang = "sync"] pub trait Sync {} pub const CONST1: u32 = 1; pub const CONST2: u32 = 2; pub struct Struct { pub field: u32, } impl Sync for Struct {} pub static VAR: Struct = Struct { field: CONST1 + CONST2, }; 

Here I get the following error:

error: binary operation + cannot be applied to type u32 [E0369]

+7
osdev rust
source share
1 answer

This is actually the expected behavior for the time being. Rust requires the add lang element to be implemented for a type, even if it is an inline type. An implementation can be completely fictitious (as long as it compiles), as it will be replaced by an inline operation .

The reason this is done is because the type of code that checks the built-in types was erroneous and complex. This simplified the type checking code, and there were already sign implementations anyway.

To do this, you need to add the following two declarations in order to be able to use the + operator even in the built-in type u32

 #[lang = "add"] pub trait Add<RHS=Self> { type Output; fn add(self, rhs: RHS) -> Self::Output; } impl Add for u32 { type Output = u32; fn add(self, _rhs: u32) -> u32 { 42 } } 

Here is a complete example that is not related to the absence of some libc files: https://play.rust-lang.org/?gist=a223d48b0f2d8533996f&version=nightly

Note that you should not create a fake implementation as shown, because you can use the built-in type in the general context where the implementation will actually be implemented

+3
source share

All Articles