Rust 注释与格式化输出

注释

编译器会忽略的常规注释:

//注释一整行
/* 注释一块 */

第二类是文档注释,用于通过工具生成HTML API文档

/// 注释一整行

//! 这是
//!    一个
//!   文档注释块

格式化输出

  • format! :将格式化的文本写入 String
  • print! :文本打印到控制台(io :: stdout)
  • println! :文本打印到控制台(io :: stdout)并换行
  • eprint! :将文本输出到标准错误(io :: stderr)
  • eprintln! :将文本输出到标准错误(io :: stderr)并换行

std::fmt包含许多traits控制文本显示的内容。下面列出了两个重要的基本形式:

  • fmt::Debug:使用{:?}标记。格式化文本以进行调试。
  • fmt::Display:使用{}标记。以更优雅,用户友好的方式设置文本格式。
fn main() {
    // In general, the `{}` will be automatically replaced with any
    // arguments. These will be stringified.
    println!("{} days", 31);

    // Without a suffix, 31 becomes an i32. You can change what type 31 is
    // by providing a suffix. The number 31i64 for example has the type i64.

    // There are various optional patterns this works with. Positional
    // arguments can be used.
    println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");

    // As can named arguments.
    println!("{subject} {verb} {object}",
             object="the lazy dog",
             subject="the quick brown fox",
             verb="jumps over");

    // Special formatting can be specified after a `:`.
    println!("{} of {:b} people know binary, the other half doesn't", 1, 2);

    // You can right-align text with a specified width. This will output
    // "     1". 5 white spaces and a "1".
    println!("{number:>width$}", number=1, width=6);

    // You can pad numbers with extra zeroes. This will output "000001".
    println!("{number:>0width$}", number=1, width=6);

    // Rust even checks to make sure the correct number of arguments are
    // used.
    println!("My name is {0}, {1} {0}", "Bond");
    // FIXME ^ Add the missing argument: "James"

    // Create a structure named `Structure` which contains an `i32`.
    #[allow(dead_code)]
    struct Structure(i32);

    // However, custom types such as this structure require more complicated
    // handling. This will not work.
    println!("This struct `{}` won't print...", Structure(3));
    // FIXME ^ Comment out this line.
}

泛型运行代码作用于抽象的类型 在函数定义中使用泛型 当使用泛型来定义函数时,将泛型放在函数签名中指定参数和返回值类型的地方。 首先我们来看两个函数: fn largest_i32(list: &[i32]) ...