我有这个代码:
struct A {
names: Vec<String>,
}
impl ToString for A {
fn to_string(&self) -> String {
// code here
}
}
fn main() {
let a = A {
names: vec!["Victor".to_string(), "Paul".to_string()],
};
println!("A struct contains: [{}].", a.to_string());
}
Run Code Online (Sandbox Code Playgroud)
预期产量:
结构包含:[Victor,Paul].
实现这一特性以实现目标的最佳方法是什么?我尝试了一些奇怪的'每个'和其他变种,但每个变量都给我一个这样的尾随逗号:
维克多,保罗,
当然我可以稍后把它弹出来,但我对这种语言感兴趣所以我想知道这个的最佳实践.这只是我尝试过的一个例子,但没关系,我问的是如何最有效地做到这一点.
mal*_*rbo 18
根据该ToString
文件:
对于实现
Display
特征的任何类型,都会自动实现此特征.因此,ToString
不应该直接实现:Display
应该实现,而且您可以ToString
免费获得实现.
你可以Display
像这样实现:
use std::fmt;
impl fmt::Display for A {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let mut str = "";
for name in &self.names {
fmt.write_str(str)?;
fmt.write_str(name)?;
str = ", ";
}
Ok(())
}
}
Run Code Online (Sandbox Code Playgroud)
你不需要打电话to_string
(但你可以):
fn main() {
let a = A {
names: vec!["Victor".to_string(), "Paul".to_string()],
};
println!("A struct contains: [{}].", a);
}
Run Code Online (Sandbox Code Playgroud)
注意以下目的Display
:
Display
类似于Debug
,但是Display
面向用户的输出,因此无法导出.
如果您的意图是调试,您可以派生Debug
:
#[derive(Debug)]
struct A {
names: Vec<String>,
}
fn main() {
let a = A { names: vec![
"Victor".to_string(),
"Paul".to_string(),
]};
// {:?} is used for debug
println!("{:?}", a);
}
Run Code Online (Sandbox Code Playgroud)
输出:
A { names: ["Victor", "Paul"] }
Run Code Online (Sandbox Code Playgroud)
该Formatter
struct提供了丰富的方法集合,因此您可以编写自己的Debug
实现:
impl fmt::Debug for A {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("A")
.field("names", &self.names)
.finish()
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4535 次 |
最近记录: |