rust


How to make a vector of received size?


I have a vector data with size unknown at compile time. I want to create a new vector of the exact that size. These variants don't work:
let size = data.len();
let mut try1: Vec<u32> = vec![0 .. size]; //ah, you need compile-time constant
let mut try2: Vec<u32> = Vec::new(size); //ah, there is no constructors with arguments
I'm a bit frustrated - there is no any information in Rust API, book, reference or rustbyexample.com about how to do such simple base task with vector.
This solution works but I don't think it is good to do so, it is strange to generate elements one by one and I don't have need in any exact values of elements:
let mut temp: Vec<u32> = range(0u32, data.len() as u32).collect();
You can use Vec::with_capacity() constructor followed by an unsafe set_len() call:
let n = 128;
let v: Vec<u32> = Vec::with_capacity(n);
unsafe { v.set_len(n); }
v[12] = 64; // won't panic
This way the vector will "extend" over the uninitialized memory. If you're going to use it as a buffer it is a valid approach, as long as the type of elements is Copy (primitives are ok, but it will break horribly if the type has a destructor).
The recommended way of doing this is in fact to form an iterator and collect it to a vector. What you want is not precisely clear, however; if you want [0, 1, 2, …, size - 1], you would create a range and collect it to a vector:
let x = (0..size).collect::<Vec<_>>();
(range(0, size) is better written (0..size) now; the range function will be disappearing from the prelude soon.)
If you wish a vector of zeroes, you would instead write it thus:
let x = std::iter::repeat(0).take(size).collect::<Vec<_>>();
If you merely want to preallocate the appropriate amount of space but not push values onto the vector, Vec::with_capacity(capacity) is what you want.
You should also consider whether you need it to be a vector or whether you can work directly with the iterator.

Related Links

Is it possible to declare config tokens within a source file?
A macro with quotes around a metavariable
How do I iterate over elements of a struct in Rust?
Do we need to manually create a destructor for a linked list?
Is it possible to create a macro to implement builder pattern methods?
Safely traversing a directed acyclic graph
Borrowing reference in structure
Is only using references the most idiomatic/efficient for “big” structures?
How to write a method that adds `self` as a mutable trait reference to a collection?
How do I modify a value after matching on it?
Drop a Rust void pointer stored in an FFI
Iterate two vectors and the rest of the larger one
How do I implement Clone/Copy for an enum that contains a String?
Modeling embedded hardware in Rust and how to have multiple mutable references cleanly?
Should I borrow or copy my small data types?
Using pointer casting to change the “type” of data in memory [duplicate]

Categories

HOME
oracle
memory
list
livecode
filesize
docker-cloud
jint
joomla3.2
onvif
polymer-2.x
azure-graph-api
multi-step
xbap
django-rq
pywinauto
pygobject
google-sites
bazaar
yii2-basic-app
data-type-conversion
sharedpreferences
sybase-ase
morris.js
spreadsheetgear
network-analysis
history.js
python-imageio
basex
bitbake
microprocessors
javax.persistence
location-services
infopath2010
john-the-ripper
knights-tour
microsoft-certifications
kendo-listview
markov-chains
creation
nppexec
formsauthenticationticket
spinner
xvfb
cargo
djcelery
oauth2
swfupload
icepdf
robust
minikube
linq-to-excel
axis
realstudio
nonlinear-functions
webvtt
exc-bad-access
mura
openerp-6
petsc
deviare
decoder
nsrunloop
dmarc
always-on-top
dojo-build
rails-engines
utf-16
mercurial-extension
gdl
nastran
cfwheels
gitlab-omnibus
gql
search-form
darwin
org-babel
tree-structure
quercus
rfc5545
mathematical-expressions
tidyr
mojo
famo.us
dnsjava
mfmessagecomposeview
boolean-algebra
progress-db
google-code-prettify
arel
days
icenium
voice-recording
cakeyframeanimation
hardcode
differentiation
filelock
kernel32
django-pagination
bass
chunking
tessellation

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App