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


Rust String.reserve_exact用法及代码示例


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

用法

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

确保此 String 的容量大于其长度 additional 字节。

考虑使用 reserve 方法,除非您绝对比分配器更了解。

Panics

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

例子

基本用法:

let mut s = String::new();

s.reserve_exact(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_exact(8);

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

相关用法


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