4 ms·
> That's why many modern programming languages like Go and Zig define strings as a simple array of bytes. I'd argue this is not in fact a modern approach but r
by arcticbull 4y ago
> That's why many modern programming languages like Go and Zig define strings as a simple array of bytes.
I'd argue this is not in fact a modern approach but rather a pretty dated one.
Modern language string API design instead leans into 'views' of the underlying depending on what you are trying to do with it.
- Transmission and storage: UTF-8 bytes.
- Parsing: code points.
- Editing: grapheme clusters.
- Rendering: pixels.
It doesn't make sense to consider a random assortment of bytes to be a 'string', that's just an array of random bytes - and the language almost certainly already has a better type for that like a vector of 8-bit unsigned values or a slice type. Strings should be opaque - but always valid - encoded data to be sensible and differentiated from a slice type.
Zig seems to be even worse than Go, requiring null-termination instead of storing them as Pascal strings. This means that a valid substring requires a copy so that the substring can itself be null-terminated to be valid. Inner pointers are not valid unless to the end of the parent and therefore substrings are very expensive relatively speaking.
- kristoff_it 4y ago> Zig seems to be even worse than Go, requiring null-termination instead of storing them as Pascal strings. This means that a valid substring requires a copy so that the substring can itself be null-terminated to be valid. Inner pointers are not valid unless to the end of the parent and therefore substrings are very expensive relatively speaking. No, Zig uses slices normally (ie ptr + len). Terminators are part of the type system for the (relatively rare, mostly related to C interop) cases where you really want a sentinel value at the end of your array.
- arcticbull 4y agoI see, I misread the docs. However everything else I stand by, after all it allows you to embed invalid UTF-8 content.