How to set the max size for a string?

As String is stored on the heap, because it's size is not known, can I define a type where I know the maximum size of a given string.
Say I know that the size of a String won't be more than 255 characters, how can I set this? Because instead of dynamic allocation of the size (which may have some performance penalty), how can I manually set the max size of a String. Also, would this approach provide some performance benefit? (I do understand that String is a recursive type)
Any help is really appreciated.

You can't set a hard max size, but you can pre-allocate some memory either using String::reserve or initially with String::with_capacity

This isn't true in Rust. String is backed by Vec which is just a block of memory.

1 Like

How would an in-struct definition look like?

Just like any other string. The difference is the use of constructor.

There's no type-level way to specify this String limit in the struct. You can only deal with the capacity at runtime.

The arrayvec crate has ArrayString which would have a hard limit. You could use Box<ArrayString> if you still want it in the heap.

1 Like

Would that have any perf improvement over just using String?

If you don't need to grow the string, then in some cases Box<str> is faster, because it doesn't have to track capacity.


ArrayString tracks capacity by constant, which could generate faster code than String when doing anything that needs to check capacity. ArrayString also holds its entire capacity as a local array, which could be good (no allocator) or bad (possibly expensive to move), but that's moot if you Box it. Otherwise I would expect performance similar to String, as the rest of the API for both mostly comes from Deref to str.

1 Like

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