当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Rust String.reserve用法及代码示例


本文简要介绍rust语言中 alloc::string::String.reserve 的用法。

用法

pub fn reserve(&mut self, additional: usize)

确保此 String 的容量至少比其长度大 additional 字节。

如果选择,容量可能会增加超过additional 个字节,以防止频繁的重新分配。

如果您不希望出现这种 “at least” 行为,请参阅 reserve_exact 方法。

Panics

如果新容量溢出 usize 会出现Panics。

例子

基本用法:

let mut s = String::new();

s.reserve(10);

assert!(s.capacity() >= 10);

这实际上可能不会增加容量:

let mut s = String::with_capacity(10);
s.push('a');
s.push('b');

// s now has a length of 2 and a capacity of 10
assert_eq!(2, s.len());
assert_eq!(10, s.capacity());

// Since we already have an extra 8 capacity, calling this...
s.reserve(8);

// ... doesn't actually increase.
assert_eq!(10, s.capacity());

相关用法


注:本文由纯净天空筛选整理自rust-lang.org大神的英文原创作品 alloc::string::String.reserve。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。