相关疑难解决方法(0)

如何索引Rust中的String

我试图在Rust中索引一个字符串,但编译器抛出一个错误.我的代码(Project Euler problem 4,playground):

fn is_palindrome(num: u64) -> bool {
    let num_string = num.to_string();
    let num_length = num_string.len();

    for i in 0 .. num_length / 2 {
        if num_string[i] != num_string[(num_length - 1) - i] {
            return false;
        }
    }

    true
}
Run Code Online (Sandbox Code Playgroud)

错误:

error[E0277]: the trait bound `std::string::String: std::ops::Index<usize>` is not satisfied
 --> <anon>:7:12
  |
7 |         if num_string[i] != num_string[(num_length - 1) - i] {
  |            ^^^^^^^^^^^^^
  |
  = note: the type `std::string::String` cannot be indexed by …
Run Code Online (Sandbox Code Playgroud)

string indexing rust

27
推荐指数
4
解决办法
2万
查看次数

标签 统计

indexing ×1

rust ×1

string ×1