为什么我的 Rust 函数的参数值在打开带有 IO 缓冲区的文件后发生变化?

问题描述 投票:0回答:1

我有一个函数

get_computer
,它将
computer_key
字符串作为参数来在文件中查找它。我的代码如下:

pub fn get_computer(computer_key: String){
    
    // read the file
    let f = File::open("computer_stock.dat").expect("Error opening file"); // line 14

    // create a buffer
    let f = BufReader::new(f);

    // Storage for the Computer Data
    let mut computer_data = String::new();

    // Signify that the computer name is found
    let mut is_found = false;

    // Loop through the lines
    for lines in f.lines(){

        // Get the string from the line
        let lines = lines.unwrap();

        // Check if it's the end of the computer's information
        if is_found && lines.trim() == ";"{
            break;
        }

        // If we found the computer, change the is_found state.
        if lines == computer_key{
            is_found = true;
        }else{
            // Otherwise, continue
            continue;
        }

        if is_found{
            computer_data.push_str(&lines);
        }
    }
    println!("{}", computer_data);

}

但是,由于某种原因,当我调试它时,

computer_key
""
之后将其值更改为
Line 14
。我的主要功能只是简单地调用它:

fn main(){
    get_computer(String::from("Computer Name A"))
}

为什么会这样?打开文件对

computer_key
有什么作用吗?

我可以通过克隆

computer_key
之前的
Line 14
来解决这个问题。但是,我宁愿不这样做。

编辑:

意识到即使我只是尝试在

println!("{}", computer_key);
之前做
Line 14
computer_key
也会因为某种原因被消耗掉。也许是关于我的进口?

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

经过更多测试,我发现

computer_key
没有被消耗。我用这段代码测试了一个新项目:

// Just to test if it's about the imports
use std::fs::File;
use std::io::{BufReader, BufRead};

pub fn get_computer(computer_key: String){
    println!("{}", computer_key);
    println!("{}", computer_key);
    println!("{}", computer_key);
    if computer_key == "Computer Name A"{
        println!("YES");
    }

}

fn main(){
    get_computer(String::from("Computer Name A"))
}

调试后,终端打印出

YES
,但在VSCode Debugger Variable View中,它包含
""
。除非我把它放入
watch lists
,否则它会正确显示。

我不知道为什么,但这是调试器或 VsCode 的错误。我不知道发生了什么,但我在 VsCode 中使用 CodeLLDB。如果你们有这方面的信息,请给我一些资源或链接。谢谢。

rust io buffer
1个回答
0
投票

经过更多测试,我发现 computer_key 没有 被消耗掉。我用这段代码测试了一个新项目:

这是我看到的:

你在某处设置断点吗?程序运行完成后,我不希望任何变量有任何值,我注意到 vscode 甚至不会在 VARIABLES 下列出变量名称。

然后我可以让调试器为变量显示空字符串

""
的唯一方法是如果我做这样的事情:

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

pub fn get_computer(computer_key: String){
    println!("{}", computer_key);
    println!("{}", computer_key);
    println!("{}", computer_key);
    if computer_key == "Computer Name A"{
        println!("YES");
    }
}

fn main(){
    let mut my_arg = String::new();
    my_arg.push_str("Computer Name B");  //ADD BREAKPOINT HERE
    get_computer(my_arg);
}

© www.soinside.com 2019 - 2024. All rights reserved.