with as constructor
with as a constructor sets one value among a type while using default values
for the rest.
with as in “<Type> with specific setting.”
#![allow(unused)] fn main() { impl<T> Vec<T> { // Initializes memory for at least N elements, len is still 0. fn with_capacity(capacity: usize) -> Vec<T>; } }
-
withcan appear as a constructor prefix, most commonly when initializing heap memory for container types.In this case, it’s distinct from
newconstructors because it specifies the value for something that is not usually cared about by API users. -
Ask the class: Why not
from_capacity?Answer:
Vec::with_capacityas a method call scans well as creating a “Vec with capacity”. Consider howVec::new_capacityorVec::from_capacityscan when written down, they do not communicate what’s going on well.