简体   繁体   中英

cannot index into a value of type `char`

I'm writing a simple hobby programming language in Rust but i'm getting stuck in this error(i'm trying to translate c code, and i'm kinda new to this lang):

error[E0608]: cannot index into a value of type `char`
  --> src/lexer.rs:28:19
   |
28 |         lexer.c = lexer.src[lexer.i];
   |                   ^^^^^^^^^^^^^^^^^^

This is the code:

pub struct LexerStruct {
    src: char,
    src_size: usize,
    c: char,
    i: u32,
}

pub fn init_lexer(src: char) -> LexerStruct {
    let lexer: LexerStruct = LexerStruct {
        src,
        src_size: src.len_utf16() as usize,
        i: 0,
        c: '\0',
    };

    lexer
}

fn lexer_advance(lexer: LexerStruct) {
    if ((lexer.i as usize) < lexer.src_size && lexer.c != '\0') {
        lexer.i += 1;
        lexer.c = lexer.src[lexer.i];
    }
}

The combination of char* data, size_t size in C is something that exists in a type in Rust: the slice type . It's exactly that, a pointer to an array and a length.

Note that char in Rust is actually a u32 carrying a unicode character. The exact translation of char* would be &[u8] .

So a direct transcription of your C struct to Rust would be:

pub struct LexerStruct<'a> {
    src: &'a [u8],
    c: char,
    i: u32,
}

If src is a human readable text anyway, then it would be much easier to use a string slice instead, as it is equivalent (it's internally also a &[u8] , but comes with a bunch of nice string manipulation functionality):

pub struct LexerStruct<'a> {
    src: &'a str,
    c: char,
    i: u32,
}

Both of those carry the lifetime <'a> because the do not own the data in src , they just point to it. If your original source code exists during the entire lifetime of the Lexer, then this is actually what you want, as it makes the Lexer zero-copy.

If you insist, however, that your Lexer should own the data, then you need to copy it and store it in either a Vec<u8> or a String , depending on your preference. Like in the slice type, those are equivalent, with String having a bunch of extra functionality for string maniuplation.

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