Is there any difference between clear() and truncate(0) on a String?

681 Views Asked by At

If s is a Rust String, is there any difference between calling s.clear() and s.truncate(0)? According to the documentation, neither will affect the capacity, and both will reduce the length to zero. Follow-up question, assuming they have the same identical result, which one is more idiomatic?

1

There are 1 best solutions below

3
tunnuz On

According to the std source code, clear is implemented as truncate(0), so they are identical, see

#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn clear(&mut self) {
    self.truncate(0)
}

As for the follow-up question, if clear exists my assumption would be that it is preferable to use it.