1

I read the document of Rust core library and found that core implement the primitives like i32, bool, usize...

And I check the source code, it do so basically like:

impl i32 {
    // const number
    int_impl! { i32, i32, u32, 32, 31, -2147483648, 2147483647, 8, "0x10000b3", "0xb301",
    "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
    "[0x12, 0x34, 0x56, 0x78]", "", "" }

    ... // methods
}

But when I do so, I got a error E309:

error[E0390]: cannot define inherent `impl` for primitive types
  --> src/main.rs:50:6
   |
50 | impl i32 {}
   |      ^^^
   |
   = help: consider using an extension trait instead 

I am just wondering how core library do that? I think I follow the same syntax too.

MrZ
  • 166
  • 1
  • 1
  • 11
  • 1
    Per the answer in the linked question: _"You can't directly implement methods on types outside of your own crate. "_ and `core` practically owns the primitive types. Not to mention that both `core` and `std` are built with access to non-stable language features. – E_net4 Aug 12 '22 at 08:27
  • @E_net4thecommentflagger But if I define a type outside the crate, I think it should show error `E0116: cannot define inherent "impl" for a type outside of the crate where the type is defined`. Why rustc use different error here? Just curious. – MrZ Aug 12 '22 at 09:02
  • Because additional constraints exist, _on top_ of the one mentioned. Note also that error messages are not necessarily stable, and may change or be improved as new versions arrive. For instance, in the linked question, the error message was of the form _"error[E0390]: only a single inherent implementation marked with `#[lang = "usize"]` is allowed for the `usize` primitive"_. The message was changed probably because the `lang` directive could overwhelm users who do not need to know about it in practice. – E_net4 Aug 12 '22 at 09:05

0 Answers0