如何为 Vec T 分配空间在锈? [英] How to allocate space for a Vec<T> in Rust?

查看:35
本文介绍了如何为 Vec T 分配空间在锈?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个Vec<T>并为它腾出一些空间,但我不知道该怎么做,而且令我惊讶的是,官方几乎没有有关此基本类型的文档.

I want to create a Vec<T> and make some room for it, but I don't know how to do it, and, to my surprise, there is almost nothing in the official documentation about this basic type.

let mut v: Vec<i32> = Vec<i32>(SIZE); // How do I do this ?

for i in 0..SIZE {
    v[i] = i;
}

我知道我可以创建一个空的 Vec 并用 pushes 填充它,但我不想这样做,因为我并不总是这样做知道,当在索引 i 处写入一个值时,如果一个值已经插入那里了.出于明显的性能原因,我不想写这样的东西:

I know I can create an empty Vec<T> and fill it with pushes, but I don't want to do that since I don't always know, when writing a value at index i, if a value was already inserted there yet. I don't want to write, for obvious performance reasons, something like :

if i >= len(v) {
    v.push(x);
} else {
    v[i] = x;
}

当然,我也不能使用 vec! 语法.

And, of course, I can't use the vec! syntax either.

推荐答案

您可以使用 vec!,特别是 vec![elem;计数].例如:

You can use the first syntax of the vec! macro, specifically vec![elem; count]. For example:

vec![1; 10]

将创建一个包含 10 个 1Vec<_>(_ 类型将稍后确定或默认为 i32).赋予宏的elem 必须实现Clone.count 也可以是一个变量.

will create a Vec<_> containing 10 1s (the type _ will be determined later or default to i32). The elem given to the macro must implement Clone. The count can be a variable, too.

这篇关于如何为 Vec T 分配空间在锈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆