乐趣区

关于rust:rust学习读取文件第一次使用lib文件

第一步:cargo new minigrep 创立一个 miigrep 初始化我的项目

第二步:编辑 lib.rs 文件:

use std::fs;
use std::error::Error;


#[derive(Debug)]
pub struct Config<'a> {
    pub query:  &'a str,
    pub filename:  &'a str,
}

impl Config<'_>{pub fn parse_config1(args: &[String]) ->  Result<Config, &'static str> {if args.len() < 3 {panic!("门路谬误");
        }
        let query = &args[1];
        let filename = &args[2];

        Ok(Config { query, filename})
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>>{let contents = fs::read_to_string(config.filename)?;

    println!("With text:\n{}", contents);

    Ok(())
}

第三步:编辑 main.rs 文件:

use std::env;
use std::process;

use minigrep::Config;

fn parse_config(args: &[String]) -> Config {let query = &args[1];
    let filename = &args[2];

    Config {query, filename}
}


fn main(){let args: Vec<String> = env::args().collect();

//    let config = parse_config(&args);
    let config = Config::parse_config1(&args).unwrap_or_else(|err| {println!("Problem parsing arguments: {}", err);
        process::exit(1);
    });;

    println!("{:?}", config);

    println!("Searching for {}", config.query);
    println!("In file {}", config.filename);

//    run(config);

    if let Err(e) = minigrep::run(config) {println!("错误信息: {}", e);

        process::exit(1);
    }

//    let text = fs::read_to_string("C:\\Users/kunt/Desktop/rgba.txt").unwrap();
//    println!("读取到的文件内容:\n{:?}", text);

}

如此就能够读取正确文件名称的文件了:

应用命令:cargo run query_any file_address

D:\learn\minigrep>cargo run as C:\\Users/kunt/Desktop/rgba.txt
   Compiling minigrep v0.1.0 (D:\learn\minigrep)
warning: unnecessary trailing semicolon
  --> src\main.rs:21:8
   |
21 |     });;
   |        ^ help: remove this semicolon
   |
   = note: `#[warn(redundant_semicolons)]` on by default

warning: function is never used: `parse_config`
 --> src\main.rs:6:4
  |
6 | fn parse_config(args: &[String]) -> Config {
  |    ^^^^^^^^^^^^
  |
  = note: `#[warn(dead_code)]` on by default

warning: 2 warnings emitted

    Finished dev [unoptimized + debuginfo] target(s) in 0.57s
     Running `target\debug\minigrep.exe as C:\\Users/kunt/Desktop/rgba.txt`
Config {query: "as", filename: "C:\\\\Users/kunt/Desktop/rgba.txt"}
Searching for as
In file C:\\Users/kunt/Desktop/rgba.txt
With text:
插入数据测试
退出移动版