移除注释的Rust脚本仅选中首行时为何残留空行?如何修复?
Rust 注释移除脚本的空行残留问题
问题描述
以下是一段用于移除代码注释的Rust脚本:
use anyhow::{Context, Result}; use std::io::{self, Read}; fn main() -> Result<()> { let mut buffer = String::new(); io::stdin() .read_to_string(&mut buffer) .with_context(|| "Failed to read from stdin")?; let modified_buffer = buffer .lines() .map(|line| { if line.trim().starts_with("//") { // If the line is a comment, return an empty string String::new() } else if let Some(pos) = line.find("//") { // If there's an inline comment, return the line up to the comment line[..pos].trim().to_string() } else { // If there's no comment, return the line as is line.to_string() } }) .filter(|line| !line.is_empty()) // Remove empty lines resulting from full line comments .collect::<Vec<String>>() .join("\n"); println!("{}", modified_buffer); Ok(()) }
测试场景:
输入两行内容(注释行+带注释的代码行)时,输出正常:
输入:// This is a comment x = 1 // This is a comment输出:
x = 1仅输入单行注释时,脚本会输出一个多余的空行:
输入:// This is a comment输出(空行):
原因分析
当输入仅为单行注释时,脚本的处理流程导致了空行输出:
- 注释行被
map转换为空字符串 filter过滤掉空字符串,最终得到空的字符串列表- 空列表通过
join("\n")生成空字符串 println!("{}", modified_buffer)会自动在输出内容后追加换行符,空字符串加换行符就形成了一个空行
修复方案
只需要在打印前判断处理后的内容是否为空,仅当内容非空时执行打印操作即可:
修改脚本末尾的打印逻辑:
// 替换原来的 println!("{}", modified_buffer); if !modified_buffer.is_empty() { println!("{}", modified_buffer); }
修改后,当输入仅为注释行时,脚本不会输出任何内容;当输入包含有效代码时,输出效果和原来一致。
内容的提问来源于stack exchange,提问作者wyc
相关产品推荐
相关产品推荐

