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

移除注释的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
    

    输出(空行):

原因分析

当输入仅为单行注释时,脚本的处理流程导致了空行输出:

  1. 注释行被map转换为空字符串
  2. filter过滤掉空字符串,最终得到空的字符串列表
  3. 空列表通过join("\n")生成空字符串
  4. println!("{}", modified_buffer)会自动在输出内容后追加换行符,空字符串加换行符就形成了一个空行

修复方案

只需要在打印前判断处理后的内容是否为空,仅当内容非空时执行打印操作即可:

修改脚本末尾的打印逻辑:

// 替换原来的 println!("{}", modified_buffer);
if !modified_buffer.is_empty() {
    println!("{}", modified_buffer);
}

修改后,当输入仅为注释行时,脚本不会输出任何内容;当输入包含有效代码时,输出效果和原来一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 13:34:56