【问题标题】:How to return slice of strings using indices?如何使用索引返回字符串切片?
【发布时间】:2022-06-15 04:45:39
【问题描述】:

我开始阅读 rust book 并尝试重新实现一些类似于我使用 Go 制作的 site 的东西。

我从文本文件中读取来创建博客文章,但我很难使用字符串索引。这是代码:https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=fa71b50c9f88e66d7d22fe82278b5c10

#[derive(Debug)]
struct Post {
    Title: String,
    Description: String,
    Tags: String,
    Content: String,
}

fn main() {
    let text_file = "Title: artitle\n\
    Description: article description\n\
    Tags: rust, tips\n\
    Content: This is the text content.";
    
    let post = create_post(text_file);
    
    println!("{:?}", post);
}

fn create_post(text: &str) -> Post {
    let title_index = text.find("Title: ");
    let desc_index = text.find("Description: ");
    let tags_index = text.find("Tags: ");
    let content_sep = text.find("Content: ");
    
    Post {
        Title: text[title_index..desc_index].to_string(),
        Description: text[desc_index..tags_index].to_string(),
        Tags: text[tags_index..content_sep].to_string(),
        Content: text[content_sep..].to_string(),
    }
}

它给了我这个错误:

error[E0277]: the type `str` cannot be indexed by `std::ops::Range<Option<usize>>`

我正在四处寻找索引字符串,但现在让我感到困惑。有什么建议吗?

【问题讨论】:

标签: rust slice


猜你喜欢
  • 1970-01-01
  • 2017-01-15
  • 2016-08-29
  • 1970-01-01
  • 2022-01-16
  • 2016-07-30
  • 1970-01-01
  • 1970-01-01
  • 2011-11-29
相关资源
最近更新 更多