Skip to content

G.TYP.STR.01 在实现Displaytrait 时不应调用to_string() 方法

【级别】 要求

【描述】

对某一类型实现 Displaytrait 的同时会自动为其实现 ToString trait。此时若调用 to_string 的 话,将会造成无限递归以及栈溢出。

【反例】

Rust
use std::fmt;

struct Structure(i32);
impl fmt::Display for Structure {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 
    write!(f, "{}", self.to_string()) // 不符合
  } 
}

【正例】

Rust
use std::fmt;

struct Structure(i32);
impl fmt::Display for Structure {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "{}", self.0) // 符合
  } 
}