ragingSloth
ragingSloth

Reputation: 1104

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, e.g. 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?

Upvotes: 0

Views: 504

Answers (2)

huon
huon

Reputation: 102306

You need to import the trait to be able to call their methods, e.g.

#![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::*;.

Upvotes: 5

Shepmaster
Shepmaster

Reputation: 432139

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 {} }

Upvotes: 2

Related Questions