[solved]Newbie:Is there a generic length of an array constant?


I'm trying to write my first library in Rust. I want to define a bitset type big enough to hold a bit for each item in a constant array of strings passed into a constructor. It sounds simple enough but there doesn't seem to be a trait or macro defined for that purpose yet as far as I can see. Any hints?

Thanks in advance!

Do you mean, you want to find out the number of elements you have in a slice or vector passed into your function?

let my_slice=[1,2,3];

println!("Length of slice: {}", my_slice.len());

let my_vec = vec![1,2,3,4,5,6];

println!("Length of vector: {}", my_vec.len());

I must be misunderstanding your question because that seems too simple...

That's it! What reference are you looking at to find all the methods of each type? The hard part is going to be coercing the allocation into a custom type size so that if there are more than 32 elements that I change the type to contain the membership set to be a u64 instead of a u32.

For size of any in-memory object you should be using usize, not u32 or u64 - that's what it was designed for.

For example, here's the reference on the slices you were looking for in this topic: slice - Rust

Thanks for the link! The reason I want to use the smallest size I can fit into is that there will be literally dozens of these bitsets all over the code and all of them will need to be serialized into a file at some point.

Just remember Knuth's sage comment: "Premature optimization is the root of all evil". Code, benchmark, then micro-optimize.

Fair enough. I'm writing cross platform file access though and usize isn't portable for writing to a file.

I thought of another, better way to do it: since the elements will be unique to each set and not repeated in any others, I can store the index that it needs to be in in a single byte per item.

If the max bitset size is not yet known, you could define a symbolic type for the integer type that you want to use to represent a bit set:

type bitset = u64;  // or u32 or u128 or …

To avoid endianness issues on different platforms, which apply to any multi-byte numeric type, I personally would try to use the bitflags crate, and if that didn't work out I might use

const MAX_BITSET_BYTES = 4;       // can be resized as needed
type bitset = u8[MAX_BITSET_BYTES];