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

'Unresolved name' inside macro despite 'ident' designator
Casting away lifetime constraints?
Re-using a range for iteration
How to convert DateTime<UTC> to DateTime<FixedOffset> or vice versa?
Redefine trait for infix operators
Result has no method called “unwrap()”?
Wrapping a Rust struct in a C++ class
How to create a String directly?
Acessing data from a global struct, gives error “borrowed value does not live long enough”
captured variable does not outlive the enclosing closure [duplicate]
PI constant is ambiguous
Calling an impl method from another impl method
compilation of openssl-sys fails with `openssl/hmac.h: No such file or directory`
Indexing a String
Importing mio::tcp::TcpStream but get std::net::tcp::TcpStream
It is possible to always have Cargo show warnings?

Categories

HOME
python-2.7
firebase
plesk
mpdf
freeradius
activex
hdfs
autocomplete
u-boot
graphdb
responsivevoice
cuba-platform
amazon-elb
complexity-theory
distributed-computing
fresco
nose
multiple-tables
home
adminlte
cmake-gui
android-custom-view
amazon-mws
pe
neo4j.rb
pymongo
cell
mod-wsgi
raima
python-appium
bonita
ibm-connections
fusion
google-play-developer-api
vcenter
memory-fences
buildforge
subclassing
landscape
jade4j
django-crispy-forms
telephonymanager
ng-repeat
microsoft-ui-automation
mars-simulator
suds
oauth2-playground
angular-datatables
autorelease
ilrepack
cordova-ios
subforms
test-data
http-basic-authentication
ptvs
glassfish-4.1
hmmlearn
ternary-operator
elastic4s
multi-touch
s-function
jsonix
gcloud-node
dpkg
ajaxmin
rails-engines
maximize
preferenceactivity
ioctl
enunciate
grinder
deeplink
place
jnlp
search-form
fantom
shoes
python-curses
mxe
datagridcomboboxcolumn
cout
inputbox
storing-data
nidaqmx
jini
webaii
tabletools
armv6
mft
illuminate-container
acitree
virtual-channel
chefspec
jquery-cycle
proc-open
examine
ntlmv2
ckeditor.net
onconfigurationchanged
audiotoolbox
popup-blocker
image-scanner
jzmq
kobold2d
uploading
acpi
type-safety
sigar
rtd
css-friendly
asp.net-mvc-views
3des
eaccelerator
j2mepolish
powergui

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