DEV Community

drake
drake

Posted on

Rust单元类型(空元组)

  • Rust单元类型只有一个值(),宽泛意义上就是空数组;可以理解为特殊的元组
  • 虽然可以理解为特殊的元组,但是并不属于元组的子集,因为Rust中元组一定不能为空,为空的就不是元祖了;Rust中元组最少得包含一个元素,故Rust在数据类型设计上做了严格的区分,将()拎出来单独做了个数据类型叫“单元类型”;(从这里也能够看到Rust语言设计的严格区分思想,严谨、“精致”)
  • 这个单元类型主要功能就是指代一个函数没有返回值,比如main函数
  • 单元类型可以赋值给一个变量,但是不能够被常规打印

如果这么写一定会报错

fn main() {
    let a = ();
    println!("{}",a);
}

Enter fullscreen mode Exit fullscreen mode
    Checking ruststudy v0.1.0 (/Users/shixiaolong/Documents/ruststudy)
error[E0277]: `()` doesn't implement `std::fmt::Display`
 --> src/main.rs:4:19
  |
4 |     println!("{}",a);
  |                   ^ `()` cannot be formatted with the default formatter
  |
  = help: the trait `std::fmt::Display` is not implemented for `()`
  = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
  = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)

For more information about this error, try `rustc --explain E0277`.
error: could not compile `ruststudy` due to previous error
Enter fullscreen mode Exit fullscreen mode

大概意思是println这个宏针对于单元类型,没有对应的方法课调用

需要切换为下面这种打印方式

fn main() {
    let a = ();
    println!("{:?}",a);
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)