Hacker News new | ask | show | jobs
by maemre 1724 days ago
Rust's str also checks things like whether you're trying to read in the middle of a character. Rust also has several related string types like Path, CStr and OsStr to make sure the strings passed to the relevant APIs are well-formed. You can also use &[u8] if you want a slice of bytes or ascii string--it has several string methods implemented in the standard library as well.

I like Rust's approach of having purpose-specific string types that may differ (e.g. if your OS is using UTF-16 encoded strings but the C strings are just arrays of bytes). It guarantees that the programmer checks/converts the string is in/to the correct form, or just let the program panic with .unwrap(), when interfacing with the external world. It makes the program safe and makes the potentially expensive string conversion calls explicit. Also, I think valid UTF-8 strings is a good default.

I haven't used Zig yet (I haven't found a good use case for it), it seems closer to C both in spirit and in implementation while removing some foot guns.

1 comments

Specialized string types like Path, CStr and OsStr are stdlib types though (as they should be), not built into the language (AFAIK at least). Such high level "API enforcement" types also make sense in Zig. The question is rather whether something like Rust's 'str' should be builtin or also provided in the stdlib.
Oh, that makes sense as an interesting question. I think, similar to API enforcement types, it is a good idea to separate strings from "byte strings" if the "core" language/library uses strings (which Rust does as part of panic!, one can argue that panic! or assert! should not be part of the core though). It is a hard problem, as Python's transition to Python 3 showed.

str could have a part of "core" library.

Is Rust `str` builtin?

I thought it was just a `struct str([u8]);` (a dynamically-sized type).

It is built in. It was almost switched to be exactly that before 1.0, but IIRC it provided no real upsides and several downsides. There was a PR with the discussion but I can’t find it right now.