const 函数中的字符串切片

问题描述 投票:0回答:1

如何在 const 函数中进行字符串切片?

const fn cya_first_char(inc: &str) -> &str {
    &inc[1..]
    //  ~~~~~ Error: cannot call non-const operator in constant functions
}
rust constants slice
1个回答
0
投票

str
没有太多const方法,但是
as_bytes
有,并且
[u8]
有一个const
split_at
方法。然后您可以使用
str
将其变回
std::str::from_utf8

const fn take_first_byte_of_str(s: &str, i: usize) -> &str {
    let Ok(s) = std::str::from_utf8(s.as_bytes().split_at(i).1) else {
        panic!("first character was more than one byte");
    };
    s
}

const fn cya_first_char(inc: &str) -> &str {
    take_first_byte_of_str(inc, 1)
}
© www.soinside.com 2019 - 2024. All rights reserved.