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!
alice
May 4, 2020, 10:41am
#2
You should use the Vec<char>
type for this.
Hyeonu
May 4, 2020, 10:45am
#3
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
alice
May 4, 2020, 10:56am
#5
You are not asking for a fixed size vector. You are asking for a vector with variable size.
1 Like
bluss
May 4, 2020, 11:07am
#6
You can have a fixed size Vec the Zen way: you have a vec, and you don't change its size
That said, there are two closely related dynamic size linear containers:
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!
system
closed
August 2, 2020, 11:07am
#8
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.