简体   繁体   中英

How do I access core traits like StrExt when using #![no_std]?

I'm trying to write some Rust with #![no_std] set. I am trying to iterate over a str one character at a time; however none of the usual techniques seem to work. When I try to access the characters via a function provided by str, eg for c in s.char_indices() or for c in s.chars() I receive the error:

type &str does not implement any method in scope named ___

My understanding was that str was a part of core and therefore any traits it implements should be available in no_std . Is there a way to access this functionality, or an alternate way to iterate over a str ?

You need to import the trait to be able to call their methods, eg

#![no_std]
extern crate core;

use core::str::StrExt;

fn foo(s: &str) {
    for c in s.char_indices() {}
}

core also provides an alternative prelude , which includes the functionality in std::prelude that is available in core . You can import it like use core::prelude::*; .

Is core::str::StrExt automatically available though? I don't have the setup to compile something with ![no_std] , but I got past a few hoops in the Playpen by adding

#![no_std]
#![feature(lang_items)]

extern crate core;
use core::str::StrExt;

fn main() {
    let s = "Hello";
    let mut cnt = 0u8; 

    for c in s.chars() {
        cnt += 1;
    }
}

#[lang = "stack_exhausted"] extern fn stack_exhausted() {}
#[lang = "eh_personality"] extern fn eh_personality() {}
#[lang = "panic_fmt"] fn panic_fmt() -> ! { loop {} }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM