You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust编程:用户输入与文件行对比遇不稳定特性报错,求解决方案

Rust:用户输入与文件行匹配的错误解决及优化方案

问题描述

我尝试将用户输入与fruits.txt文件中的行进行对比,代码基本成型,但遇到如下编译错误:

error[E0658]: use of unstable library feature 'option_result_contains'
--> src/main.rs:19:20
|

s if s.contains(&ask) => println!("{} is a fruit!", ask),
^^^^^^^^

= note: see issue #62358 https://github.com/rust-lang/rust/issues/62358 for more information

For more information about this error, try rustc --explain E0658.
error: could not compile learn_arrays due to previous error

我尝试了多种Rust匹配方式,当前代码是最接近可行的版本,不会出现字符串与行类型不匹配的报错,代码如下:

use std::fs::File;
use std::io::{BufReader, BufRead, Error, stdin};

fn main() -> Result<(), Error>{
    let path = "fruits.txt";

    let input = File::open(path)?;
    let buffered = BufReader::new(input);

    let mut ask = String::new();
    stdin()
        .read_line(&mut ask)
        .expect("Failed to read line");

    let ask: String = ask.trim().parse().expect("Please type a valid string!");

    for line in buffered.lines() {
        match line {
            s if s.contains(&ask) => println!("{} is a fruit!", ask),
            _ => println!("{} is either not in the list or not a fruit", ask),
        }
    }

    Ok(())
}

请问是否可以使用该不稳定特性,或者有更优的方法实现用户输入与文件行的对比?


解决方法

关于不稳定特性的使用

不建议使用这个不稳定特性。它仅在Rust的nightly开发版本中可用,稳定版编译器会直接报错。依赖不稳定特性会导致代码无法在生产环境的稳定Rust中编译,且后续版本更新可能修改或移除该特性,兼容性和稳定性都没有保障。

更优的实现方案

原代码存在两个核心问题:

  1. buffered.lines()返回的迭代器元素是Result<String, Error>,直接对Result调用contains会触发不稳定特性错误——稳定版的Result类型并没有contains方法。
  2. 原代码会遍历文件每一行并逐行输出结果,逻辑不合理:应该是找到匹配行就输出“是水果”,遍历结束仍无匹配才输出“不是水果”。

修正后的优化代码如下:

use std::fs::File;
use std::io::{BufReader, BufRead, Error, stdin};

fn main() -> Result<(), Error> {
    let path = "fruits.txt";

    let input = File::open(path)?;
    let buffered = BufReader::new(input);

    let mut ask = String::new();
    stdin()
        .read_line(&mut ask)
        .expect("Failed to read line");
    // 无需parse,trim后直接转String即可
    let ask = ask.trim().to_string();

    // 遍历文件行,检查是否存在匹配项
    let is_fruit = buffered.lines()
        // 过滤掉读取失败的行,若需严格处理错误可改用?
        .filter_map(|line| line.ok())
        // 这里用trim后完全匹配,若需包含匹配可改为line.contains(&ask)
        .any(|line| line.trim() == ask);

    if is_fruit {
        println!("{} is a fruit!", ask);
    } else {
        println!("{} is either not in the list or not a fruit", ask);
    }

    Ok(())
}

关键优化点:

  • 处理lines()返回的Result类型:用filter_map过滤读取失败的行,保证后续操作的是有效字符串。
  • 使用any方法一次性检查是否存在匹配行,避免重复输出结果。
  • 移除多余的parse调用:trim()后的字符串直接转String即可,无需额外解析。
  • 匹配逻辑灵活调整:若需要“输入字符串包含在某一行中”而非完全匹配,将line.trim() == ask替换为line.contains(&ask)即可,此调用的是稳定版String的contains方法,无兼容性问题。

内容的提问来源于stack exchange,提问作者Jaw_dropper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 09:30:38