← All languages
Rust function of the day
Random

String::capacity

Return the current capacity of the String in bytes.

Description

String::capacity returns the number of bytes the String can hold without reallocating. This is always greater than or equal to the string's length.

When a String needs to grow beyond its capacity, it allocates a new buffer and copies the existing data. By using with_capacity or reserve, you can minimize these reallocations when the final size is approximately known.

This is an O(1) operation and is useful for performance tuning and debugging memory usage.

Example

let s = String::with_capacity(10);
assert!(s.capacity() >= 10);
assert_eq!(s.len(), 0);

Reference