蓝色天空.知识 · 实践 · 创造
我的收藏
Rust 教程目录 29章
Rust / LEARN BY DOING

Rust 输出到命令行

详解 Rust 命令行输出宏 println! 与 print! 的区别、{} 占位符与 0 基位置索引复用、{{ 与 }} 花括号转义及反斜杠转义规则,并以离线格式解析器实测验证。

学完这一章,你能够

  • 详解 Rust 命令行输出宏 println! 与 print! 的区别、{} 占位符与 0 基位置索引复用、{{ 与 }} 花括号转义及反斜杠转义规则,并以离线格式解析器实测验证。

输出宏 println! 与 print! 的基本用法

向命令行输出文本是学习任何编程语言起步阶段的必备手段。新手看到 `println!("Hello World")` 时常好奇为何 `println` 后带有感叹号 `!`——在 Rust 中感叹号用于标识“宏(macro)”而非普通函数(宏会在编译期展开并检查格式串合法性)。标准库提供 `println!()` 与 `print!()` 两种主要输出宏:二者都以格式字符串作为首个参数、后接可变数量的数据参数,唯一差异在于 `println!()` 会在末尾自动追加一个换行符;与 C 语言 `printf` 的 `%d`/`%s` 不同,Rust 使用花括号 `{}` 作为通用显示占位符。

在基础示例中,声明 `let a = 12;` 并调用 `println!("a is {}", a);`,在配备工具链的环境下通过 `rustc main.rs` 编译并运行 `./main` 后,命令行将输出 `a is 12`。本站离线格式解析器实测对比了 `print!`(输出 `"a is 12"`,无换行)与 `println!`(输出 `"a is 12\n"`)的精确字节差异。

位置索引占位符与花括号转义

当同一变量需要在格式字符串中多次出现时,不必像 `println!("a is {}, a again is {}", a, a);` 那样重复传参,而是可以在花括号中填入从 `0` 开始的整数索引:`println!("a is {0}, a again is {0}", a);`。花括号内的数字会按数组下标方式索引后续参数,既减少重复传参也支持调整输出顺序(例如 `{1}-{0}-{1}`)。离线格式解析器同时验证了参数数量不足或索引越界会在解析阶段被立即拦截。

若希望在结果中直接打印字面量花括号 `{` 或 `}`,需在格式字符串中分别成对写作 `{{` 与 `}}`,因此 `println!("{{}}");` 的实际输出是 `{}`。至于换行符 `\n`、制表符 `\t`、双引号 `\"` 与反斜杠 `\\` 等其他常用转义字符,则与 C 系语言一样采用反斜杠前缀表示。离线脚本已逐项核对 `{{}}`、`{{{0}}}` 以及反斜杠转义输出。

离线运行 Rust 格式字符串解析器,验证 print!/println!、位置参数与花括号转义

含完整源码 · 156 行
展开查看收起
python
"""Offline Rust semantic verification lab for Chapter 05 (println)."""
import json
import shutil

VERSION = "CPython 3.12.14 offline Rust semantic verifier (rustc absent)"


def rust_format(template: str, *args) -> str:
    """Minimal Rust format_args! evaluator supporting {}, {n}, {{ and }}."""
    out = []
    i = 0
    auto_idx = 0
    n = len(template)
    while i < n:
        ch = template[i]
        if ch == "{":
            if i + 1 < n and template[i + 1] == "{":
                out.append("{")
                i += 2
                continue
            end = template.find("}", i + 1)
            if end == -1:
                raise ValueError("unclosed '{' in format string")
            spec = template[i + 1 : end]
            if spec == "":
                if auto_idx >= len(args):
                    raise IndexError("not enough positional arguments")
                out.append(str(args[auto_idx]))
                auto_idx += 1
            elif spec.isdigit():
                idx = int(spec)
                if idx >= len(args):
                    raise IndexError(f"argument index {idx} out of range")
                out.append(str(args[idx]))
            else:
                raise ValueError(f"unsupported placeholder spec: {spec!r}")
            i = end + 1
        elif ch == "}":
            if i + 1 < n and template[i + 1] == "}":
                out.append("}")
                i += 2
                continue
            raise ValueError("unmatched '}' in format string")
        else:
            out.append(ch)
            i += 1
    return "".join(out)


def case_print_vs_println_newline():
    p1 = rust_format("a is {}", 12)
    p2 = p1 + "\n"
    expected = {
        "print_output": "a is 12",
        "println_output": "a is 12\n",
        "println_ends_with_lf": True,
        "rustc_installed": False,
    }
    actual = {
        "print_output": p1,
        "println_output": p2,
        "println_ends_with_lf": p2.endswith("\n") and not p1.endswith("\n"),
        "rustc_installed": shutil.which("rustc") is not None,
    }
    return {
        "name": "print_vs_println_newline",
        "summary": "对比 print! 与 println! 宏在末尾换行符上的差异及单占位符格式化结果",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_positional_and_repeated_placeholders():
    seq_form = rust_format("a is {}, a again is {}", 12, 12)
    idx_form = rust_format("a is {0}, a again is {0}", 12)
    reordered = rust_format("{1}-{0}-{1}", "A", "B")
    expected = {
        "sequential": "a is 12, a again is 12",
        "indexed": "a is 12, a again is 12",
        "reordered": "B-A-B",
    }
    actual = {"sequential": seq_form, "indexed": idx_form, "reordered": reordered}
    return {
        "name": "positional_and_repeated_placeholders",
        "summary": "验证顺序 {} 与 0 基下标 {0}、{1} 重复引用可变参数的等价输出",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_brace_and_backslash_escapes():
    braces = rust_format("{{}}")
    mixed = rust_format("{{{0}}}", 42)
    backslash_text = rust_format("line1\n\t\"{}\"", "ok")
    expected = {
        "escaped_empty_braces": "{}",
        "wrapped_value": "{42}",
        "escaped_newline_tab_quote": 'line1\n\t"ok"',
    }
    actual = {
        "escaped_empty_braces": braces,
        "wrapped_value": mixed,
        "escaped_newline_tab_quote": backslash_text,
    }
    return {
        "name": "brace_and_backslash_escapes",
        "summary": "验证 {{ 与 }} 转义输出花括号字面量以及 \\n、\\t、\\\" 反斜杠转义行为",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_format_argument_validation():
    errors = {}
    for label, tpl, args in [
        ("missing_arg", "{} {}", (1,)),
        ("oob_index", "{2}", (10, 20)),
        ("unclosed_brace", "{", ()),
        ("unmatched_close", "}", ()),
    ]:
        try:
            rust_format(tpl, *args)
            errors[label] = "unexpected_ok"
        except (IndexError, ValueError) as exc:
            errors[label] = type(exc).__name__
    expected = {
        "missing_arg": "IndexError",
        "oob_index": "IndexError",
        "unclosed_brace": "ValueError",
        "unmatched_close": "ValueError",
    }
    return {
        "name": "format_argument_validation",
        "summary": "验证格式字符串占位符数量不足、越界索引及未闭合花括号在解析期即被拒绝",
        "expected": expected,
        "actual": errors,
        "passed": errors == expected,
    }


def main():
    cases = [
        case_print_vs_println_newline(),
        case_positional_and_repeated_placeholders(),
        case_brace_and_backslash_escapes(),
        case_format_argument_validation(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
在离线 CPython 3.12.14 中验证 print! 与 println! 换行差异、顺序 {} 与 {0}/{1} 复用、{{}} 与反斜杠转义以及缺参/越界/未闭合花括号校验全部通过。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1193.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Rust

课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a1193.zip

下载课程关联工程包:Rust

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1215.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

可以写作 `println!("{{0}} = {0}", x);`(或 `println!("{{0}} = {}", x);`):前两个成对花括号 `{{0}}` 转义为字面量 `{0}`,后面的 `{0}` 或 `{}` 负责插入变量 `x` 的值。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习