What's so complicated about it? We have String, &str, CString, &CStr, OsString, &OsStr, Cow, &[u8], [u8; N], Vec<u8>, &Path, PathBuf, Arc<str>, Box<str>, Box<[u8]>, Rc<str>, Cow<'static, str> and a couple of others. It' s not that hard...
Clone On Write. I haven't used it much, but basically it's either a reference or a owned value, and you can switch between them depending on your needs
For the uninitiated:
- String: resizable utf8 string on the heap
- &str: reference to any utf8 string, static or on the heap
- CString: resizable null-terminated string on the heap (for FFI compatibility only)
- &CStr: Reference to the above
- OsString: Resizable string of whatever the OS uses for commands and environment and such. Utf8, Utf18, invalid characters, whatever
- &OsStr: Reference to the above
- Cow<str>: copy on write
- &[u8]: u8 buffer (slice), wide pointer with location & length. This is the underlying type for many of the above
- [u8; N]: u8 array of length N
- Vec<u8>: Resizable vector of u8.
- PathBuf: OsString wrapper for working with paths
- &Path: reference to the above
Nobody uses the <str> versions of these in normal use, but these are smart pointers:
- Box<T>: Smart pointer to anything on the heap, like c++ unique_ptr
- Rc<T>: Refcounted pointer to something on the heap (not thread safe)
- Arc<T>: atomically refcounted pointer (thread safe), equivalent of c++ shared_ptr
In summary: there’s a static buffer &[u8], and a dynamic Vec<u8>. Then there’s a utf8 version of each (str/String), a null terminated version for FFI (CStr/CString), an OS-compatible version that may be utf16 (OsStr/OsString), a path wrapper on top of that (Path/PathBuf).
Sound complex? It can be, but you never need all of these. You’ll thank yourself when your program doesn’t output different things on Windows and Linux terminals, or crash when file names contain invalid characters.
Is Rust…is Rust a good/useful language? Just seeing all the possible types of strings makes it seem like a bunch of code vomit. I genuinely have no idea, my only exposure to it is people shitting all over it on here lol
I love it. Mileage varies of course, but I think people tend to enjoy it a lot after they have a couple weeks to warm up - the gist is, it makes it really hard to write incorrect code.
99% of the time you use &str or String for everything, and don’t need to care about the others. Other cases:
1. You read environment variables, paths, etc., then you get an OsStr
2. You are working with the C FFI and need CStr for minimal parts of code
3. You’re working with paths and use PathBuf. I don’t think of this as a string type, it’s more like python’s PathLib (things like file_name, canonicalize, etc)
You can convert from &str/String to any of the other types when needed - but these conversions are fallible. For example, you can’t do:
- &str -> CString if your string contains \0 (which is valid Unicode)
- Vec<u8> -> String if it’s not valid Unicode
- PathBuf -> String if it contains invalid utf8/16
(And of course you have options for how to handle these cases, e.g. just lossy convert with the replacement character).
Weird at first? Sure. But in return, you skip:
- Wacky #defines that switch between char* and wchar_t*
- Manual path handling that doesn’t work across Linux-windows
- You know that String/&str is _always_ utf8 and you _always_ know the length, unlike char* (unsized memory buffer? Null terminated string? Something else?)
- Your program doesn’t break in bizarre ways because it assumes that file names or terminal input have valid encoding or are UTF8
Handling these things in C or C++ is just…. yuck. I think the proper handling turns into way way worse code vomit than just having these types available, which you don’t need to touch if you don’t need them. (If you’re coming from something like Python, it more or less handles all this for you of course)
Anyway, YMMV but I do think they made some very good decisions, which do make it so writing correct code is easier than writing incorrect code.
My background has been in Java, a bit of Python, and I’ve been doing a ton of JS/REACT (which obviously includes HTML and CSS), and I’m still fairly new using programming in a professional setting, so anyone who uses any of the C languages is like a wizard to me. Is Rust built on top of one of the C languages like Python is? It sounds like it is, but I want to be sure. Also how have you used it in personal or professional settings? I will literally try anything once if it seems useful/fun lol
Oh… yes, it’s quite different from Python. There’s no runtime or garbage collector like Python, Java or Go has. Instead it compiles down to machine code like C or C++ does, for performance: but, the compiler disallows a lot of errors that you’d kind of write “by default” in those languages. Things like segfaults, buffer overruns, invalid pointers, etc, so the result is your code runs more correctly like Python or Java would (but without the runtime overhead).
I realize that makes 0 sense, especially to somebody who hasn’t dabbled much with C. I would kind of recommend learning some C before Rust - you really have to shoot yourself in the foot 500 times with C or C++ to appreciate what Rust does.
That being said: a bit of dabbling never hurts, and the community is open to helping people of all programming backgrounds. And if your company is thinking about replacing any of the Java applications for performance reasons, Rust would be the correct direction to look at this time (compared to C++)
That’s definitely something I’d have to take into account in the future, as I want as many tools in my belt as possible. unfortunately right now, I only work as analyst at my company. The goal is to transition to the IT department or software engineering somewhere else after a full year at my current company. From what you’re describing, does that mean that there’s no real error handling as is more common with other languages?
Rust can control machines at low level, and these are all ways that programmers have come up to represent strings in machines, and optimizations for them.
If it looks like vomit, it's just the result of humanity being creative dealing with an ugly world.
There’s so many because each of those is a combination of a given character encoding and ownership.
* String/str -> known-length UTF-8
* CString/CStr -> the way C does it (null-terminated ASCII)
* OsString/OsStr -> the way your OS does it (UTF-8 for Unix, UTF-16 for Windows)
Ownership:
* &str/&[…]Str -> Reference to a string owned by someone else. I can’t delete it or change it.
* &mut str/&mut […]Str -> Mutable reference to a string owned by someone else. They’ve allowed me to change its contents, but not delete it or change its length.
* […]String -> Owned by me. I can change it’s contents and delete it whenever I want. I can give other code references to it.
Then there’s those other three that are kinda strings, but really just used more when dealing with encoding/serialization stuff:
* Vec<u8> -> Vector of unsigned bytes. Similar to std::vector<char> in C++. Has conversions to and from other owned string types.
* [u8; N] -> N-length array of unsigned bytes.
* &[u8] -> Slice of unsigned bytes, which is a reference to some array of unsigned bytes. It could be just part of a larger array (hence the name “slice”). Has conversions to from other non-owning string types.
By the way, the bit about slices also applies to the other reference string types. They could also be slices of larger strings.
PathBuf/&Path are like OsString/&OsStr but with methods to enable easily working with paths. You can push and pop directories and file names, and they’ll handle representing that as an OS-appropriate path.
Box, Rc, and Arc are owning pointer types used for allocation. Box is the simplest: it uniquely owns its contents. This is like most owning types in rust.
Rc is a reference-counted shared pointer. Ownership can be shared by cloning the Rc, which increments a counter tracking the number of references. When someone is done with the Rc, the decrement the counter. If they find it to be zero, they know that they were the last owner of the Rc, so they go ahead and actually delete the data it owned.
Arc is Rc, but the counter is atomic so that cloning is safe with multiple threads.
Box, Rc, and Arc have generally immutable content, with extra methods to acquire it mutably if possible. It’s always possible for Box, and possible for Rc and Arc as long as there are no other remaining references to the same content.
Cow<‘static, str> is a clone-on-write reference to a statically-allocated string. As long as I don’t need to change the underlying string, the reference points to same statically-allocated content. I’m allowed to change it though (it’s an owning reference), and if I do, the Cow will clone the static string into a new allocation so that I don’t affect the original.
So yeah, definitely not that bad.
(i’m going entirely off of memory here so this might not be 100% accurate)
95% of the time you only use `String` and `&str`, for 'owned' and 'borrowed' strings. Some others are for specific use cases, like `CString` to interact with C
Well technically there are some edge cases where the complier suddenly decides to be dumb about something and leaks some memory. You just need to know when and avoid those edge cases.
On my Rust training I learned that memory leaks are memory safe in the definition of Rust's memory safety. That's why cycling references are still valid and safe Rust code which are leaking memory.
But with all the other safeties it is won't happen casually.
Guy in the corner:
"Oh shit, how did I get that job?? I mean, yes, I can program in my sleep, but I'm getting paid $30/hr and PTO can roll over. So, when will HR find out that I don't have any college experience, and I have two basic certifications"
I am a front end dev and while typescript is pretty great, JavaScript is a complete shambles.
I will happily acknowledge that most languages are probably better than JavaScript.
I’ll be honest… I’ve never had this thought. I’m in C# and Python daily, and C++ infrequently.
I dunno where this language elitism comes from. The job requires a language, I use it.
I’m starting to dabble, mostly so I could help my daughter with her programming class for middle school coding class but being in online school at her own pace she ran through half the course in about two weeks. Her teachers recommending her for AP courses for college creds for future classes.
I never understood why people are so willing to die on the hill of a programming language.
Most languages have use-cases that make sense for them, based on the tools and frameworks as well as the focus of the common libraries.
Some languages are objectively bad though (Objective-C, I'm talking about you).
honestly, people bashing languages usually have no experience in writing in them and do it just because they heard those jokes from someone else and took them seriously...
python -> yes, it's slow, but you can script damn fast in it
c++ -> performance goes brrrr
rust -> compiler becomes your friend
php
Look, I hate Python, but it’s a good language. I use it constantly.
I love R/C++, but they’re not the best use case for writing lots of stuff (or learning to program!) I use it when it’s feasible, but often I need to use what everyone knows.
Scheme (and it’s mother language Lisp) are a great meme, and assumably beloved language, but I don’t hear a lot of my industry contacts using them daily.
IDL is a trash language, but it was used for decades as the common language, and it has some of the nice benefits of FORTRAN.
Regex is absolutely fucking incomprehensible, but it’s great for slicing strings!
I could go on, but languages are all like that—they either have legitimate reasons someone hates them, or they aren’t used.
I hate the documentation, the constant package conflicts, the syntax is kind of bad sometimes, and any time it has to import another language, all hell is unleashed in the form of writing everything to a single pointer since “it doesn’t _do_ pointers”
Regex is definitely a defined syntax and behavior independent of programming language. Whether it's a programming language is a bit different of a matter, but I would say it exists as its own language that many PLs have support for.
> behavior independent of programming language
That's not even really true though. Different languages have different flavors of regex, at best you can say you can say its a syntax that is semi-independent from of programming languages.
There's a definite set of standards, which is why things like [Regex Cheatsheets](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Cheatsheet) work. Yes, languages have variations, but they all conform to some set of rules that define a standard of sorts. It'd be like saying that TCP isn't a protocol unto itself because there are variations in the different implementations.
> Regex is absolutely fucking incomprehensible, but it’s great for slicing strings!
Best description of regex ever.
When I'm *creating* a regex pattern it all makes sense. When I look at it an hour later?
"WTF is this mess? What does it even do?"
I agree on R. It’s too terse. The document is difficult to understand. It’s like, here are five examples, go figure out the rest yourself.
I read a funny comment on Reddit.
You have a problem and think, ah, this will be a good one for R. Well. Now you have two problems.
Anytime someone says “Python slow use … it’s faster” ask them “okay, … might be faster than Python, but is YOUR … code faster than Python?”
Also Python has language features like generators, which significantly increase performance over iteration in other languages. Right tool for the job sort of thing
Poorly written Python is slow. And perfectly optimized C++ will be faster than perfectly optimized Python.
But most of the time this is irrelevant, because nobody is bothering to write perfectly optimized code in either language. Heck, half the time code with the best performance actually has poor maintainability and extensibility.
There's a reason Python is one of the most used languages in the world. The milliseconds of difference it takes to display a terminal prompt before running C code from a library and spitting out a CSV is almost always completely irrelevant, but the hours you save avoiding random pointer errors or overriding class templates is worth its weight in gold.
With modern processors, language performance is irrelevant for about 95 percent of programming project anyways. If a performance improvement isn’t noticeable to the end user, then you shouldn’t waste your time worrying about it.
Way too many engineers are hung up on micro optimisations that are completely inconsequential in real world scenarios.
True. solving Leetcode problems in python helps a lot in focusing more towards the idea than just being stuck with debugging language related complications.
Imho It also is the only proper business viable option for certain types of tasks. Like sure, I could do my language processing in C++ or even Java.
I also probably could continue to hit myself with hammer until everything stops hurting, and it’d be equivalent the same experience.
Yeah it’s never a great sign to me when an engineer is overly hung up on a certain language / framework / IDE. All those things are just tools to do a job. If you can’t do your job using different tools, then you’re probably not a great programmer.
Really, because the main sentiment I see is that this subreddit is full of conflict adverse juniors who think every language is as good as every other language based on flimsy truisms.
To be fair, college basically teaches that the most important thing about programming is efficiency and getting really optimized Big O values.
And when you actually get into the industry you discover that CPUs are actually pretty fast and aren't intimidated by your customized CRUD GUI. The only thing that really matters is whether or not you can hit your deadlines and deliver on time, and that iteration speed is more important than execution speed in 99% of scenarios.
Now my answer to "what language should we use?" is always "what language will get a working solution the fastest with the least amount of headache for the team available?"
That answer isn't necessarily the most efficient, but it's the one that's most important to my company, so it's the one that happens.
I use Ruby, and if I sum all milliseconds you gain from doing something in Rust instead of Ruby, the results will still be less than the development time difference
I don't get why people hate one of the best scripting languages largely used, specially PHP 8. The only annoying thing is the $var_name, I hate having to press w button everytime I need to use a variable.
Bro, PHP doesn't have strong typing. Comparing variables in PHP is the same as comparing them in JavaScript. If you don't want this to happen you are using the wrong language.
PHP is the only language to be bold and instead of calling it something boring like „split“ they went with „explode“, hell yeah I want to explode my strings!
You can learn it pretty fast. Start with variables char, int, float etc. (No pointer yet)(and don't to string operations just print formatted to test) and arithmetic operations. Then look at functions, structs, typedefs and enums. After this try to find some pre processing things to find out like include, ifdef, define. Learn more about the compiler and linker. Somewhere between functions and pre processing macros you should try to understand arrays and pointer because that will be pretty much your program logic. Look at further functions provided in header files like memcpy, memcmp, malloc, free. If you do arrays and pointer you can start doing strings (is the same)
Java, I know it's bad, I'm just doing it, there are better languages than java, but I like old school, and probably after I have some experience on it, gonna move to another language, but being honest I shouldn't have picket for being my first language, was hard, but it's natural.
Really genius coders know their programming language is the most sucking one and the only reason that it work out for them is the massive intellect of themselfs...
I’m convinced people just throw language terminology around out of boredom. Whenever people say they are “learning” a new language it means they looked at a youtube vid for 20 minutes then went back to the one language they *actually* know.
Do people really feel this way? I feel more like "Wow look at all these smart people knowing multiple languages. I should spend more time studying like them."
Humankind in a nutshell, just replace "programming language" for religion, ideology, gaming platform, sports club, whatever you want.
People are tribalist in nature, we just need to more common sense...
210 Comments
Intelligent_Event_84@reddit
sup3rar@reddit
Makel_Grax@reddit
sup3rar@reddit
capi1500@reddit
iArena@reddit
trevg_123@reddit
Praying_Lotus@reddit
trevg_123@reddit
Praying_Lotus@reddit
trevg_123@reddit
Praying_Lotus@reddit
renrutal@reddit
Depress-o@reddit
PopularIcecream@reddit
TurtleTheSeaHobo@reddit
sup3rar@reddit
metaltyphoon@reddit
MrMars05@reddit
arisatox@reddit
Intelligent_Event_84@reddit
ladananton450@reddit
VladVV@reddit
konstantinua00@reddit
Jazzlike_Tie_6416@reddit
DomeE__@reddit
Kyyken@reddit
elixir-spider@reddit
Kyyken@reddit
konstantinua00@reddit
GamingWithShaurya_YT@reddit
Conseqdbh@reddit
GamingWithShaurya_YT@reddit
IHeartBadCode@reddit
Kyyken@reddit
wegorz9@reddit
BerserkerVTuber@reddit
wut101stolmynick@reddit
remy_porter@reddit
Blaz3@reddit
StrangelyBrown@reddit
arobie1992@reddit
ObeyTime@reddit
FatLoserSupreme@reddit
remy_porter@reddit
l4z3r5h4rk@reddit
fedex7501@reddit
d1rect0ry@reddit
Ok-Transition7065@reddit
Blaz3@reddit
Maveko_YuriLover@reddit
Inevitable-Cellist23@reddit
kzlife76@reddit
FoundOnTheRoadDead@reddit
xCreeperBombx@reddit
noname942@reddit
kzlife76@reddit
jaybee8787@reddit
JollyJuniper1993@reddit
mrSunshine-_@reddit
ltethe@reddit
TheRitalinCommando@reddit
tboy1492@reddit
scorpsec@reddit
tboy1492@reddit
BandidoDesconocido@reddit
tboy1492@reddit
Danteynero9@reddit
tboy1492@reddit
ariel3249@reddit
OkCarpenter5773@reddit
dontBeOffensivepls@reddit
Lukester__@reddit
OkCarpenter5773@reddit
dontBeOffensivepls@reddit
astro-pi@reddit
DeepGas4538@reddit
astro-pi@reddit
skesisfunk@reddit
arobie1992@reddit
skesisfunk@reddit
arobie1992@reddit
DarkSideOfGrogu@reddit
astro-pi@reddit
HunterIV4@reddit
DarkSideOfGrogu@reddit
Ok-Transition7065@reddit
Jazzlike_Tie_6416@reddit
DarkSideOfGrogu@reddit
windigo3@reddit
astro-pi@reddit
TrageDK@reddit
top_of_the_scrote@reddit
ilovecssbutithatesme@reddit
Character-Education3@reddit
CAlexZA@reddit
xCreeperBombx@reddit
Zumokoto77@reddit
nickmaran@reddit
xCreeperBombx@reddit
d1rect0ry@reddit
brianl047@reddit
Empty-Ad-3257@reddit
Northujhuinjjnhj@reddit
Iron_Garuda@reddit
oshaboy@reddit
FoundOnTheRoadDead@reddit
dumnaya@reddit
kevdog824@reddit
HunterIV4@reddit
kevdog824@reddit
karmahorse1@reddit
dumnaya@reddit
routamorsian@reddit
dumnaya@reddit
l4z3r5h4rk@reddit
skesisfunk@reddit
karmahorse1@reddit
SinkPanther@reddit
Chryssie@reddit
400double@reddit
BurnTheBoats21@reddit
HunterIV4@reddit
cryptomonein@reddit
fedex7501@reddit
WorkFromHomeOffice@reddit
JustAPotatoThatsIt@reddit
ploud1@reddit
Thunder_Child_@reddit
mgray88@reddit
meyerdutcht@reddit
Jock-Tamson@reddit
sargsauce@reddit
Jock-Tamson@reddit
Appropriate-Scene-95@reddit
Jock-Tamson@reddit
Giulio_otto@reddit
Successful-Note6589@reddit
FatLoserSupreme@reddit
noname942@reddit
Automatic-Choice-794@reddit
Jazzlike_Tie_6416@reddit
thegameoflovexu@reddit
Jazzlike_Tie_6416@reddit
thegameoflovexu@reddit
Jazzlike_Tie_6416@reddit
thegameoflovexu@reddit
dddaemonnn@reddit
AntyCo@reddit
Goat1416@reddit
Appropriate-Scene-95@reddit
Dark_Reaper115@reddit
golgol12@reddit
PrometheusAlexander@reddit
Appropriate-Scene-95@reddit
No-Menu-768@reddit
Semicolon_87@reddit
DeProgrammer99@reddit
Appropriate-Scene-95@reddit
DeProgrammer99@reddit
agrophobe@reddit
Cerbeh@reddit
CaseoJKL@reddit
Ionsus@reddit
Jasinto-Leite@reddit
EternalNosferatu@reddit
gepettow@reddit
planetarylaw@reddit
StrangelyBrown@reddit
OkCarpenter5773@reddit
Merecat-litters@reddit
orsikbattlehammer@reddit
alexgraef@reddit
rldml@reddit
MaybeACoder007@reddit
suprmiikka@reddit
SerialForBreakfast@reddit
Creeperassasin1212@reddit
Conseqdbh@reddit
michael31415926@reddit
Spiritual-Image7125@reddit
AldoLagana@reddit
hold_the_fuckup@reddit
Metal-Due@reddit
tetryds@reddit
jaximus_downing@reddit
abilengarbra@reddit
DarkfulLight@reddit
casualrocket@reddit
CST1230@reddit
Ok-Transition7065@reddit
AntiSocial_Vigilante@reddit
MrDragon@reddit
Metal-Due@reddit
_Vicix@reddit
kzlife76@reddit
z3n777@reddit
JollyJuniper1993@reddit
niky45@reddit
MetricJester@reddit
GamingWithShaurya_YT@reddit
codemise@reddit
MaZeChpatCha@reddit
SameRandomUsername@reddit
bananabajanana@reddit
Kosmux@reddit
ecmascript_writer@reddit
nick_jr7@reddit
InFm0uS@reddit
Low-Equipment-2621@reddit