|
|
|
|
|
by tialaramex
1075 days ago
|
|
The fundamental type isn't what you're thinking of as "string" roughly C++ std::string What's fundamental is the reference type, because that's the type you're going to use much more often, this is correctly a slice type, it refers to some bytes, I said above &[u8] is the least capability that's reasonable, and that's at last what std::string_view gives C++ This is one of the many fundamental choices Rust made that's much cleverer than it looks. The str type (some bytes which are promised to be UTF-8 text) is a language feature, a slight improvement on [u8] that's core to the language, however String is just a library type, albeit a very heavily optimized library type. A $1 micro controller might well have some use for &'static str, the immutable slice reference, e.g. to talk about some text baked into its firmware, but it doesn't have a heap allocator, it's not about to waste precious RAM on a dynamic allocator, and so it doesn't need String. |
|
The str type you mention is a nice feature, and in the future when I will have switched to Rust or whatever, I might use it to write my programs in 5 lines less.
While in C I have to use C's "slice" type: char x[] = "Hello". I know it's not quite as good since if I was to pass this around, I would have to make a pointer + length representation for this. If I needed it, it can be automatized from string literals: struct String(const char *buffer, size_t size); #define STRING(lit) (String){lit "", sizeof lit - 1}. Or char buffer[256]; my_api(buffer, sizeof buffer);
For the few situtations where string manipulation is required, it's just not a real problem.