Unknown array length

Hi everyone!
Im very new to rust and Im trying to create a struct with an unknown array length until the implementation:

struct MyStruct {
    arr: [char; ?] // I dont know the length yet...
}
impl MyStruct {
    fn new(length: i32) -> Self {
        arr:[char; length] // The length as a parameter 
    }
}

Is this possible? Or how can I do something like this?

Thx!

You should use the Vec<char> type for this.

Also note that the Rust's char type has size of 4 bytes, as it represents an Unicode scalar value. Maybe what you want is String, an owned growable buffer of UTF-8 string?

1 Like

Thanks alice!

But can I have a fixed size Vec in rust? Cant find any documentation about it

You are not asking for a fixed size vector. You are asking for a vector with variable size.

1 Like

You can have a fixed size Vec the Zen way: you have a vec, and you don't change its size :wink:

That said, there are two closely related dynamic size linear containers:

  • Box<[u8]>
  • Vec<u8>

And the box one doesn't support growing, so you will be less tempted to modify its length (you can only do so by recreating a larger box).

1 Like

Sorry if the title is misleading, I think I can go with a Vec instead.

Thanks!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.