() 无法使用默认格式化程序进行格式化

问题描述 投票:0回答:1

mystring.rs

pub fn return_string() {
  return "Some String"
}

然后在 main 中,我想打印这个字符串

mod mystring;
const test = config::return_string();
println!("{}", test);

我得到的错误是

println!("{}", test);
   |                    ^^^^ `()` cannot be formatted with the default formatter
rust
1个回答
4
投票

假设你的最小可重现示例是:

pub fn return_string() {
    return "Some String"
}

fn main() {
    const test = return_string();
    println!("{}", test);
}
error: missing type for `const` item
 --> src/main.rs:6:11
  |
6 |     const test = return_string();
  |           ^^^^ help: provide a type for the constant: `test: ()`

error[E0308]: mismatched types
 --> src/main.rs:2:12
  |
1 | pub fn return_string() {
  |                        - help: try adding a return type: `-> &'static str`
2 |     return "Some String"
  |            ^^^^^^^^^^^^^ expected `()`, found `&str`

error[E0277]: `()` doesn't implement `std::fmt::Display`
 --> src/main.rs:7:20
  |
7 |     println!("{}", test);
  |                    ^^^^ `()` 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` (in Nightly builds, run with -Z macro-backtrace for more info)

解决方案

您的代码中有两个错误:

  • 不要在函数内部使用
    const
    。使用
    let
    let
    一个不可变的值。
    let mut
    是可变的。
    const
    仅用于不可变全局变量。
  • 您缺少
    return_string()
    函数的返回类型

我在这里假设返回类型是

&str
,但它也可能必须是
String
。欲了解更多信息,请搜索
&str vs String

第三,作为次要注释,如果不需要,请尽可能避免

return
。如果您不使用
;
结束函数,则函数的最后一行将自动成为返回类型。

pub fn return_string() -> &'static str {
    "Some String"
}

fn main() {
    let test = return_string();
    println!("{}", test);
}
Some String

错误信息的解释

错误消息显示

()
不可打印。

()
是空类型,类似于 C++ 中的
void
。由于您没有注释
return_string()
的返回类型,Rust 假定它是
()
。并且
()
无法直接打印,至少不能使用
Display
格式化程序。

不过,您可以使用

Debug
格式化程序打印它:

pub fn return_void() {}

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

请注意,与 C++ 相反,

()
实际上是一种可存储类型,即使它的大小为
0
并且其中没有数据。这使得仿制药的事情变得更加容易。过去,需要能够处理 void 返回值的 C++ 模板对我来说是一个主要的痛苦因素,因为它们总是需要特殊情况。
    

© www.soinside.com 2019 - 2024. All rights reserved.