简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM