【发布时间】:2014-08-23 21:26:34
【问题描述】:
我试图在 Rust 中索引一个字符串,但编译器抛出一个错误。我的代码(Project Euler 问题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
}
错误:
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 `usize`
String 不能被索引是有原因的吗?那我该如何访问数据呢?
【问题讨论】:
-
这个答案可能会有所帮助:stackoverflow.com/questions/22118221/…