All Rust string types explained

  Переглядів 142,182

Let's Get Rusty

Let's Get Rusty

День тому

Today we are diving into the surprisingly complicated world of strings. Not only will we learn about the fundamental data structures behind strings, but we'll also discuss how string are implemented in C and more importantly how they are implemented in Rust.
FREE Rust cheat sheet: letsgetrusty.com/cheatsheet
Chapters:
0:00 Overview
0:32 String fundamentals
3:26 Strings in C
4:39 Strings in Rust - safety
5:30 Strings in Rust - Strings and &str
7:37 Strings in Rust - &'static str
8:47 Strings in Rust - Box str
10:03 Strings in Rust - Rc str
10:36 Strings in Rust - Arc str
11:04 Strings in Rust - Byte representations
12:05 Strings in Rust - String literals
13:13 Strings in Rust - Specialized strings
15:13 Strings in Rust - Interoperability strings
18:23 - Summary

КОМЕНТАРІ: 262
@letsgetrusty
@letsgetrusty 7 місяців тому
📝Get your *FREE Rust cheat sheet* : letsgetrusty.com/cheatsheet
@mohaofa1544
@mohaofa1544 2 місяці тому
In C, you can use the strlen() function to determine the length of a string. The sizeof() operator does not give you the length of a string, but rather the size of the array that holds the string. So correct code would be something like this Char string[]="hello world!"; Char buffer[strlen(string)+1]; Most Rust have skill issues regarding on C and yet they talk about it because they want to pormote SAFETY FEATURE that expert C coder don't need - good for webdev and python programmer - hope you stay away from C because you really don't understand it
@blenderpanzi
@blenderpanzi 7 місяців тому
Note: While ASCII characters are stored in bytes, it only uses 7 bits. Meaning it only supports 128 distinct values (not 256 distinct values). There are encodings that extend ASCII to use the 8th bit, though, like e.g. ISO-8859-1 (aka latin1). But that's not ASCII.
@Brandlingo
@Brandlingo 7 місяців тому
Sadly a little known fact. And only this 7 bit ASCII range is identical for many encodings such as many Windows codepages or even UTF-8 which makes them backwards compatible.
@alexwhitewood6480
@alexwhitewood6480 7 місяців тому
True. ASCII: 7 bit (128 chars) "Extended" ASCII: 8 bit (256 chars)
@CharlieLavers
@CharlieLavers 7 місяців тому
For historical reason the 8th bit was traditionally used in ascii as a parity bit as a rudimentary integrity check
@lumberjackdreamer6267
@lumberjackdreamer6267 6 місяців тому
To be more precise, it’s 127 characters in ascii plus the ‘\0’ Characters from 1 to 31 are control characters. Then the first real character is at 32, it’s the space. Character 126 is tilde. 127 is DEL.
@fswerneck
@fswerneck 5 місяців тому
@@lumberjackdreamer6267 they are 128 as 0 is included.
@chrissaltmarsh6777
@chrissaltmarsh6777 7 місяців тому
A (mostly retired) person who has used (still use) C. C is concentrated, very very smart, for its age and still pretty important. If you want to understand the cleverness of Rust, write your experiments in C, fall down the holes, and you will understand why it is clever. (In general, try to understand one level down) (Oh, and get close to the metal. There is the fun!)
@EbonySeraphim
@EbonySeraphim 7 місяців тому
To be more clear, you have to try to write "portable" C with an additional zinger of handling data with more than ASCII or ISO-8859-1 encoding. If you are writing C for a known and targetted platform + OS, strings and paths really aren't that hard to manage.
@htspencer9084
@htspencer9084 7 місяців тому
Yeah, I'm glad that the rust community as a whole still respects and shows deference to C. It's not about one being better than the other, it's about different overall philosophies :)
@apestogetherstrong341
@apestogetherstrong341 7 місяців тому
Your computer is not a PDP-11, you are not "close to the metal" with C.
@chrissaltmarsh6777
@chrissaltmarsh6777 7 місяців тому
@@apestogetherstrong341 One of the computers was a PDP, and close to the metal is what I did - and still do, but not with a PDP. And C can hit the hardware addresses. Pretty close to the metal I would say.
@JDLuke
@JDLuke 6 місяців тому
@@apestogetherstrong341 I dunno, man. When a string is still a raw sequence of bytes and the pointer to it could be NULL, pointing to the zeroeth byte of the heap, or maybe it's already been free()ed (no good way to know) I'd say that's as close to metal as generally feasible. Of course, if you're running in some virtualized environment, the metal is isolated to some degree regardless of the language you used.
@chrraz
@chrraz 7 місяців тому
The Rc and Arc examples are actually a little misleading. The Rc::from() call will actually clone the str slice that it is given. Just like the Box, the Rc owns its data. All the Rc::clone calls will not clone the string data further though :)
@MRL8770
@MRL8770 7 місяців тому
I'm not even sure why Rc was used in this case. A regular slice would do the trick, no copying and reference-counting involved. A better example would be if the original string wasn't 'static and went out-of-scope, while the reference-counted copy gets retained.
@Alguem387
@Alguem387 7 місяців тому
I want an array of characters! YOU CANT HANDLE AN ARRAY OF CHARACTERS!!!
@PixelThorn
@PixelThorn 3 місяці тому
Very funny, thank you 👍
@andrei5680
@andrei5680 7 місяців тому
I would like to thank you for creating such well explained videos. As a rust novice I learned so much from your videos.
@letsgetrusty
@letsgetrusty 7 місяців тому
Thank you for watching :)
@ishi_nomi
@ishi_nomi 7 місяців тому
Great content. Those types may seems messy but they feels so natural as a c programmer.
@jamesdi7261
@jamesdi7261 7 місяців тому
The diversity of types is a safety feature itself because you can't simply assign one string to another without explicit conversion. It's controlled by a type system.
@OmnipotentEntity
@OmnipotentEntity 7 місяців тому
Small errata I noticed: at 18:15 the null check seems to be inverted.
@OmnipotentEntity
@OmnipotentEntity 7 місяців тому
Great video btw! Thanks for the resource.
@giladkay3761
@giladkay3761 7 місяців тому
Great video. I do feel like these videos need a bit more of the "behind the scenes" animations of how the bits are stored and handled, because they do a great job in driving the point home
@MrKaNuke
@MrKaNuke 4 місяці тому
My first CS course was in C and I never quite understood much of these concepts but your video just explained it so well. I would love to understand better how some of these C characteristics lead to security and runtime vulnerabilities and how Rust prevents them.
@ed9w2in6
@ed9w2in6 7 місяців тому
I think there's an error in the CString example ( 18:00 ). The branch for success getenv call should be execute when `!val.is_null()` is true. The negation keyword `!` is missing.
@guidow9616
@guidow9616 7 місяців тому
Wanted to point out the same, but then decided to look for it in the comments first. glad i was no the only one :)
@gottox
@gottox 7 місяців тому
Thanks for this video! If we compare the data types of rust and C, we need at least to distinguish between char * and char[] on the C side. If we want to be super correct, we also need `const char *` and `const char[]` too. Also, it's PathBuf, not PathBuff :)
@alexwhitewood6480
@alexwhitewood6480 7 місяців тому
Yeah that was super confusing when I initially started learning C.
@gottox
@gottox 5 місяців тому
@@alexwhitewood6480 tbh, C does a very good job to hide the differences through implicit lookups, but it fails in a few edgecases where it becomes really confusing. sizeof(char*) vs sizeof(char[]) being the most famous. example.
@maltamo
@maltamo 7 місяців тому
I don't get why the Rc isn't thread safe compared to Arc. Since it's immutable, the threads won't be able to modify it's value, so, why do you need to make it atomically accessible? There is no threat by only reading a shared data, or am I missing something?
@belowdecent6494
@belowdecent6494 7 місяців тому
The issue is not with the string contents but with reference counting done by Rc, Rc updates its reference count in a thread-unsafe way, thus the need for Arc
@maltamo
@maltamo 7 місяців тому
@@belowdecent6494 I see! Totally makes sense now. Thank you for your answer.
@mback3713
@mback3713 5 місяців тому
I feel that RUST fights me when I am working with internationally standardized protocols that assume ASCII formats and with tools that only care about ASCII and use that encoding as optimization. Rust needs an ANSI-C compatible ASCII-only type to interoperate with C serializations where high performance is a fundamental requirement... there are two scenarios I work with on a day to day basis where this is important: 1. processing of simple data that is ascii tag to ascii data... where the code optimization to assume ascii reduces parsing overhead. 2. processing of low level serialization standards that not only assume ascii but depend upon ascii... where unicode checks are unnecessary and degrade application performance. Rust needs string types that specify encoding. Instead of "String" it needs "String" (or some similar syntax) types. Then... String and String and String and.... any other interesting encoding can be clearly communicated and converted through standard means. Stop fighting us and provide good abstractions that don't force upon devs a one world policy... let the world be open and instead establish standards for conversion.
@okuno54
@okuno54 2 місяці тому
Assuming someone hasn't already written it... then write it yourself. All you're asking for a thin wrapper around Vec and/or &u8, and Rust gives you the ability to write that abstraction and drop it in. You just gotta do it (or more likely, find it in the ecosystem)
@svenyboyyt2304
@svenyboyyt2304 2 місяці тому
The syntax you suggest doesn't make any sense in Rust terms and encapsulating it like that would incur an overhead. Just have different types for different strings. Someone has probably already made a library for it, which you probably wouldn't need anyway because utf8 is compatible with it.
@Aucacoyan
@Aucacoyan 7 місяців тому
This is the free bible of strings! Thank you so much for the effort, this is string guide to everyone, both new and advanced alike!
@MRL8770
@MRL8770 7 місяців тому
To add to this allready great video, 'static doesn't really mean that the data is going to be there for the entire lifetime of the program. 'static is applicable anywhere when the variable is guaranteed to be unbound by any lifetime restrictions. So, you may find 'static added to trait bounds that apply to types such as Rc. You may also find &'static applied to lazily instantiated variables using the lazy_static crate.
@kreuner11
@kreuner11 7 місяців тому
C also has char16_t, Unicode library strings, other library strings like Glib probably has something like that for dynamic length strings, often a program may implement their own strings without using null termination which libc has partial support for already, etc
@avinashthakur80
@avinashthakur80 7 місяців тому
Few questions: 1. You initially said strings in rust are immutable. But later presented "&mut str" saying that it is mutable string, which allows in place transformations. What did you mean by former statement then ? 2. You said "Box" doesn't have the capacity information. By capacity, do you mean the length of string ?(usually capacity != used size). If you meant capacity as in a vector, then what is difference between "Box" and "&str" as both don't have capacity? If you meant capacity = size, then how can this string be used in reality ? As lack of size & no null-termination would mean that we can't know where the string ends.
@avishjha4030
@avishjha4030 7 місяців тому
Strings are immutable by default unless quantified by "mut". Same applies to other data types as well. Box doesn't have capacity information, i.e. not ideal for expansion. The difference between Box and &str is that Box is mutable and the owner, versus &str is immutable (you can mutate it as &mut str) and is borrowed not owned.
@anon_y_mousse
@anon_y_mousse 7 місяців тому
Nothing is mutable by default so to make it mutable you have to add the keyword mut. The capacity is used to allow resizing a string, otherwise it's just a slice, i.e. a view into another string. I suppose they thought it was cool to drop it because it saves 8 bytes, and it doesn't add a ton of complexity to the base string type. To work with an immutable string you really only need the length and pointer to the data anyway, though if they're going through all this trouble of defining multiple ways of dealing with strings they should've included a short string type that encodes the length in the first byte the way Pascal did it.
@KohuGaly
@KohuGaly 7 місяців тому
1. string slices in rust are _usually_ immutable (as in, most commonly you access a string slice through immutable reference "&str"). The mutable reference to a string slice "&mut str" is an extremely niche type to see in the wild, because there is very little you can actually do with it safely. 2. By capacity we mean the size of the allocation where the string slice is stored. In case of Box, the size of the allocation will be the same as the size of the string slice in bytes. In case of String, it may have extra memory at the end, so it doesn't have to reallocate every time the size of the string changes during modification. The String type is just Vec type (dynamically sized array), but wrapped in an API that preserves valid UTF-8 encoding in the stored bytes.
@Mankepanke
@Mankepanke 7 місяців тому
Main thing about Box is that it's an alternative to String, not &str. I.e. you want an _owned_ value, but don't want to present it as something you can/should modify and therefore don't need the capacity. If you didn't need an owned value, you should just use &str directly. This is why the video talked about Box not having the capacity inside of it.
@jma42
@jma42 7 місяців тому
> You initially said strings in rust are immutable. But later presented "&mut str" saying that it is mutable string, which allows in place transformations. He said its immutable by _default_
@kdcadet
@kdcadet 5 місяців тому
Very good level of technical detail! Thank you!
@BryanBaron55
@BryanBaron55 7 місяців тому
What an awesome video! You actually covered everything in very understandable way. God job, buddy. Keep it up.
@themisir
@themisir 7 місяців тому
18:10 correction: I believe the condition branches should be the other way around; or the condition should be negated
@exhilex
@exhilex 2 місяці тому
Loved your video❤ Easy, simple and precise detailed explanation of the cause behind each string type. Makes us realise that on the low level, how complex very simple but fundamental aspects like strings can be. Keep up the good work 👍🏻
@heynicetomeetyou
@heynicetomeetyou 7 місяців тому
Loved it, informative and straight to the point
@pramodjingade6581
@pramodjingade6581 7 місяців тому
Thank you for the detailed explanation!!
@SyamaMishra
@SyamaMishra 7 місяців тому
This is the single best reference on Strings I've seen. I'd love to know about things like OSStrExt and WTF8 too.
@simon-off
@simon-off Місяць тому
I'm finally getting around to learning rust and these videos are a great recourse! Thank you 🙏
@racum
@racum 7 місяців тому
Thank you! ...this was very clarifying!!
@Saturate0806
@Saturate0806 7 місяців тому
Excellent explanation, well done.
@keeroin
@keeroin 7 місяців тому
Great informative video! So useful!
@sachinmurali3524
@sachinmurali3524 7 місяців тому
I was really looking for this info❤❤
@voidemon490
@voidemon490 5 місяців тому
Thank you so much. because of your amazing videos I started switching to rust from TS ❤
@nikkiho
@nikkiho 7 місяців тому
Thank you for a great information.
@sbx1720
@sbx1720 7 місяців тому
This one was really good. Thanks
@ChasingShadowsz
@ChasingShadowsz 7 місяців тому
Great video, thank you! 🙏
@jongeduard
@jongeduard 7 місяців тому
Thanks for this really great video with such a complete overview! Small note however, your C string example at 17:35 has a bug. You forgot the exclamation mark in front of the is_null check, inverting your if logic. Whoopsy.
@chronxdev
@chronxdev 4 місяці тому
came here for this, I almost thought I was crazy for a sec there
@jongeduard
@jongeduard 4 місяці тому
​@@chronxdev It's also funny because it actually directly displays the reason for safe Rust code with the Option enum type and how that is only possible to extract when it actually has a value, which is what people refer to when they talk about the power of Rust's type system. And which is what you will use in most cases when not directly talking to C libraries.
@tabiasgeehuman
@tabiasgeehuman 7 місяців тому
13 seconds in I see a typo: `PathBuff`
@keenant
@keenant 7 місяців тому
💪💪💪path buff yo
@a13m34
@a13m34 7 місяців тому
Hell yeah brother 💪💪💪💪💪
@neociber24
@neociber24 7 місяців тому
Yooo buff that path 💪🏽💪🏽💪🏽
@31redorange08
@31redorange08 7 місяців тому
There's another one: ’a
@letsgetrusty
@letsgetrusty 7 місяців тому
That's not a typo 💪💪💪
@ikhlasulkamal5245
@ikhlasulkamal5245 7 місяців тому
Thanks for the video, it helps me a lot about strings xD
@_jdfx
@_jdfx 7 місяців тому
great video as usual!
@ahmadrezadorkhah9574
@ahmadrezadorkhah9574 7 місяців тому
Thanks. I needed that
@sleepybraincells
@sleepybraincells Місяць тому
incredible video jam packed with info
@sirrobertdowneysenior8080
@sirrobertdowneysenior8080 7 місяців тому
Just want to say I am on 20 years old PC and rust apps just run rocket. I love you rust developer!!! need not to say lazy electron / js devs will burn in hottest corner of hell.
@thulist
@thulist Місяць тому
Great video, very easy to follow. Subbed
@DomainObject
@DomainObject 6 місяців тому
Awesome video. Thank you!
@moigncoin4870
@moigncoin4870 Місяць тому
Gosh this is such a good video. Thank you
@1____-____1
@1____-____1 7 місяців тому
I like these more in-depth vids.
@bluebukkitdev8069
@bluebukkitdev8069 3 місяці тому
Liked for the Rc, that's good info.
@hos7012
@hos7012 7 місяців тому
this is just amazing 🎉
@EbonySeraphim
@EbonySeraphim 7 місяців тому
I don't get Arc for immutable strings. If it's immutable, why is any synchronization necessary?
@kebien6020
@kebien6020 3 місяці тому
I think synchronization is necessary for the reference counting, not for the string content.
@AsbestosSoup
@AsbestosSoup 6 місяців тому
what does it mean the we cannot use str because the size/length is not known at compile time? I see this explanation everywhere but I seem to be missing some key detail to understand correctly. If you store a string (not String) in the binary for static, read-only access, don't you have access to the slice's length, given that you need it to access it?
@zeus000.00
@zeus000.00 3 місяці тому
What exactly do you mean by 'cleanup' does it deallocate or overwrite with null bytes and then deallocates? Lets say you have a password prompt and you what to make sure the password is erased from memory after you're done with it. What would be the good datatypes to use?
@LokeshWritesCode
@LokeshWritesCode 7 місяців тому
this is so good 🙂
@petermaltzoff1684
@petermaltzoff1684 5 місяців тому
13:56 looks like on line 3 the raw string literal is missing the two hash symbols delineating the start and end. Can you have raw string literals without this hash symbol?
@ce5983
@ce5983 7 місяців тому
Can someone explain the first unsafe c string example with the overlong sequence for A 0x41 (according to the comment)? Is the problem with it just that its two bytes or that its not actually 0x41 at all? I dont understand what 0xC1, 0x81 has to do with A
@awesome_aiden
@awesome_aiden 7 місяців тому
When encoding UTF8, you may need to pad the codepoint with leading 0 bits. This is because UTF8 only stores 7-bit, 11-bit, 16-bit, or 21-bit codepoints. Overlong sequences arise when you pad the codepoint more than necessary.
@awesome_aiden
@awesome_aiden 7 місяців тому
More information is on Wikipedia. wikipedia.org/wiki/UTF-8#Overlong_encodings
@awesome_aiden
@awesome_aiden 7 місяців тому
If say, you are trying to sanitize a Windows filename, then you would want to filter out backslashes. In correctly formed UTF8, you could just remove all 0x5C bytes. Overlong backslashes could skip this check, and get converted to regular backslashes when converting to UTF16 (Windows filename).
@ce5983
@ce5983 7 місяців тому
@@awesome_aiden ah thanks 👍 hope I don't have to worry these kinds of char encoding issues anytime soon or ever lol seems like a headache and a half 😅
@TheFreeSpiritKID
@TheFreeSpiritKID 7 місяців тому
Drink a shot everytime he says shtring
@RallyGuy
@RallyGuy 7 місяців тому
1. Doesn't the `String` come with an overhead of storing the size of the string? imagine a string 4 bytes long and having a variable 4 bytes to store the size (uint32). 2. Won't the re-sizing the string add arithmetic overhead of adding/subtracting the value? whereas in c you can just assign the character after the last character to `0x0` 3. Rust strings can be implemented in C too right? just have a struct: ```c struct String { char* data; uint32 length; } ``` and then just have functions to manipulate it? 4. if Strings in rust are always UTF-8 encoded, doesn't this add a overhead in the program's performance? Because string-related function in the rust's std library will have the code that works with UTF-8 string which will add a performance overhead since working with variable-length encodings like UTF-8 have a complex logic compared to working with fixed-length encodings like ASCII, which is basically waste of CPU time because in ALOT of cases you just only need ASCII 5. A "string-slice" in C can be just another `String` struct i defined above and the `data` pointer now points to the start of the slice and `length` is equal to the size of the slice.
@ABaumstumpf
@ABaumstumpf 7 місяців тому
1 - Yes it comes with an overhead. But in general those things will be negligible. It really depends on the size of the string and how exactly it is implemented. For example many languages (C++ and Rust included) make the class quite a bit bigger - in the range of 24-32 bytes. That holds the pointer to the data, how long it is, and how much storage is reserved. So yes a very short string takes significantly more memory. 2 - Yes and no. In C you can NOT just add a character to a "string" cause a "char*" used for storing strings does not have the information of either how long it is or how much memory it has. If you do not create your own struct for that then you are doing hundreds of times more work just to add a single character. Say your string is "C string is fast" and you now want to append "er!" to finish the sentence. These are the steps you need to do: linearly search for the end of the string - and you already did way more arithmetic calculation than needed in C++/Rust. Then reallocate the string, then append "er!\0". In C++ you also most of the time have small-string-optimisation so strings shorter than 22 character are stored directly in the class without any dynamic memory involved. 3 - kinda, but you are missing some critical information and the memory-layout is bad. 4 - not really. UTF8 is a character-encoding and that has absolutely no impact on performance directly as long as you do not use the extended features. Btw C is not ACII either - it can be UTF16 (which factually is slower and more memory intensive), or even EBCDIC - so all your string-manipulations would be wrong. 5 - sure. And you just need to make sure that the underlying string is never rellocated. It would be a lot more convincing if you gave some better C-examples and not ideas that come from fresh students. C does have some major advantages but you havent touched on any of them.
@RallyGuy
@RallyGuy 7 місяців тому
@@ABaumstumpf i am still learning c so please do forgive me, so i wanted to reply to few of your points. 3. How is the memory layout of my struct bad? 4. I haven't worked with UTF-8 directly but i know that there are this things called "codepoints" and stuff which are to be handled by the code logic, so won't the UTF-8 implementation of a string function be a bit more slow because of handling all that code logic? which is fine if you're using UTF-8 strings but what if you're just using ASCII characters, won't that extra logic slow down the code a bit? and the last "unlisted" point, umm can you give some c-examples and stuff? i am quite new to C, just over a year and i still have alot of stuff to learn.
@ABaumstumpf
@ABaumstumpf 7 місяців тому
@@RallyGuy There is no problem with you just learning C - but then a video about Rust is the wrong place for such questions as those are unlikely to even get the C-code correct (if not making it intentionally bad). As for the layout: You want your fixed-size member first as that allows for allocating the entire object in 1 contiguous block of memory. This is a bit more advanced C than you would ever see in this type of video here and not something you need to know when starting with C in general, but just doing 1 malloc instead of 2 will be faster and having it in a single block of memory means that accessing the data effectively only goes through 1 indirection instead of 2. So both creation and usage of the string would be faster. "which are to be handled by the code logic" only if you are using code that needs to deal with them. The encoding has absolutely no influence on how you decide on dealing with the data. UTF8 is a superset of ASCII meaning in C you can have your "normal" Char-string and either treat it as ASCII, Latin8 or UTF8. That is up to you. If you then want to get the correct string-length and you are treating it as UTF8 then it becomes slightly more computationally intense cause you are doing more work, but you are also getting more functionality for that as just treating it as ASCII would give you the wrong result. That is a very easy to make beginner error that i have seen a couple of times with tracing. People want to write out what their program is doing but also make it look pretty so they use the bordering-symbols to print a table. And then they suddenly notice that they get misallignments and wrong formatting at best, or memory-corruption and crashes at worst cause they did not account for those symbols being more than 1 byte. If you know that you are dealing with ASCII then you would just handle the string byte-by-byte and you would have no extra overhead either. As for examples - my C is a bit rusty after doing just C++ for many years now. And sadly the last few courses i had seen were basically horrible where they started with the most archaic version of C written in a horrible error-prone style. C is a relatively old language as it was created in the 1970s, and standardised in 89. But since then the language has evolved and gotten some nice additions. In general learning-by-doing and getting some instruction-series on UKposts works, or if you can a course at your local university.
@RallyGuy
@RallyGuy 7 місяців тому
@@ABaumstumpf thanks alot!
@ABaumstumpf
@ABaumstumpf 7 місяців тому
@@RallyGuy and just cause it popped up in my recommendations: ukposts.info/have/v-deo/iaBynI5knql5rqc.html ACCU has a lot of nice videos about specific topics in relation to C and C++
@MrDujmanu
@MrDujmanu 7 місяців тому
Come up with an idea and write a Rust book, you're exceptionally good at explaining.
@KyleHarrisonRedacted
@KyleHarrisonRedacted 3 місяці тому
4:30 so don’t be lazy and either provide a big enough buffer if you’re going to use magic hard coded numbers or use one of the tiny handful of functions c has to query at run time what size is needed. It’s seriously not that bad
@petermaltzoff1684
@petermaltzoff1684 5 місяців тому
Both &str and Box save on memory by not storing the capacity. Kinda confused because he mentions the Box as an alternative to &str but states it saves on memory, as though the &str type doesnt. Am I missing something or is my confusion justified? 😂
@bozhidaratanasov7800
@bozhidaratanasov7800 3 місяці тому
Still confused about &str vs str. The memory layout of &str (pointer, length) doesn't look like the memory layout of other normal references. Is this the layout of &str or more exactly str? If so, why do we have to always use str with a reference, but not String?
@SKTTWkartrider
@SKTTWkartrider 2 місяці тому
4:32 `sizeof` is the operator rather than function in C, although it usually looks like a function by syntax
@DK1PL
@DK1PL 2 місяці тому
I am not a Rust programmer and my roots are in C. I recognize the advantages of UTF-8 strings and slices but I wonder why so many data types. Why so complicated, why a data type for each use case? String, slice and byte array (C-String) are enough. Other properties of String e.g. Heap, Stack, Const, Atomic, etc. could be handled by keywords that can be used for all other types. Additional the "r#" notation where the \" is enough. So I inevitably have the impression that Rust, just like C++, is stepping into infinite ambiguity - see also Perl. And then there's the "unsafe" option, if I opt for security, then I remain secure, don't I? In large software that is developed over years/decades it's only a matter of time before you find reasons for "unsafe" and then Rust reduces to C. So I might as well write my code in C from the beginning? 🤔
@plawzzz6629
@plawzzz6629 2 місяці тому
Great explanation. At 10:59 I had to specify the type - shared_text:Arc so it would build
@MatveyTsivinyuk
@MatveyTsivinyuk 7 місяців тому
Glad to know about all the shtring types in Rust /s
@TobiasFrei
@TobiasFrei 7 місяців тому
Great idea to present them all in one place and even including Cow 🤓👍
@flippert0
@flippert0 4 місяці тому
Apart from String and &str I only needed &[u8, N] (or &[u8]) yet. I think 99% is done with String and &str and the other types are almost never encountered in normal programs.
@tianned
@tianned 2 місяці тому
22 minutes of efficiency safety and flexibility
@6srer
@6srer 4 місяці тому
I didn't quite get the difference btwn &String and &str Literals and non-literal strings
@thecoolnewsguy
@thecoolnewsguy 7 місяців тому
Man that's too much and there are many string types you haven't mentioned. It's really very steep learning curve
@meetarthur9427
@meetarthur9427 7 місяців тому
let some_large_text: &'static str = "is already enough, you can't mutate it and it resides in binary, lives entire programm and thread safe"
@chaicblack7415
@chaicblack7415 3 місяці тому
I find it useful some c or cpp knowledge for understanding rust.
@nikitakokorev6393
@nikitakokorev6393 Місяць тому
Thank u!!
@nils3030
@nils3030 6 місяців тому
Is your Cow example at 14:51 really a good example for Cow? It doesn't show what Cow can provide, does it? I mean automatically copying the underlying data when you try to modify it.
@fcolecumberri
@fcolecumberri 7 місяців тому
Do you think Rust approach to strings is complicated? try to manage a mix of English with Japanese with only char[]
@mintx1720
@mintx1720 7 місяців тому
Now you just need to cover SmolStr, SmartString, SmallString, KString, EcoString...
@sundae6610
@sundae6610 13 днів тому
how many times I've rewatch this
@alexclazx
@alexclazx Місяць тому
Very helpful to my nap break😀
@captainfordo1
@captainfordo1 7 місяців тому
This alone makes me never want to touch Rust again. Definitely sticking with C.
@mutantthegreat7963
@mutantthegreat7963 Місяць тому
Appreciation
@yapayzeka
@yapayzeka 7 місяців тому
the below type should be &String as it is at 6:50 . to be a string slice it should be &my_string[..] or something.
@nullplan01
@nullplan01 2 місяці тому
I will note that as of C99, we have already had wchar_t for representing wide characters, and as of C23, char8_t, char16_t, and char32_t are joining in. The use of 16-bit wchar_t should be deprecated, libraries should switch to 32-bit wchar_t (which has been state of the art on UNIX since the late nineties, but Windows is slow to adapt), and legacy UCS-2/UTF-16 strings should be represented with char16_t.
@thatstupiddoll
@thatstupiddoll 7 місяців тому
Man doing a long video like this and finding small errors and nickpics after the fact must be painful, but know that this video is great and all of the explanation are amazing!
@KyleHarrisonRedacted
@KyleHarrisonRedacted 3 місяці тому
5:17 really. Guaranteed UTF8? So about this when I had to deal with when comparing two strings, a title value found inside a html payload vs a title value stored in the database, and they don’t equate because one was ascii and one was utf8 despite being exactly identical values letter for letter when looking at them in the step debugger. Was a bugger of a bug to figure out what the actual problem was but rust wasn’t guaranteeing any particular character encoding for me..
@U20E0
@U20E0 2 місяці тому
that's just cursed.
@theowillis6870
@theowillis6870 3 місяці тому
doesnt C have unint8_t* and uint8_t [] ?
@legittaco4440
@legittaco4440 2 місяці тому
4:30 Slight mistake, it should be sizeof(my_string)+1. strlen doesn’t count the null character.
@charliesumorok6765
@charliesumorok6765 3 місяці тому
in C, string *literals* are arrays of characters.
@atduyar
@atduyar 7 місяців тому
@fcolecumberri
@fcolecumberri 7 місяців тому
I am not 100% sure in rust (only like 99.99%), but if Rust uses short string optimization the same way C++ does, the image at 6:15 is technically wrong, "Hello!" would have been saved inside the pointer avoiding the need of extra memory allocation. For any string bigger than the size of the pointer, then the image would have been correct.
@jeffg4686
@jeffg4686 7 місяців тому
9/10 crab review 🦀🦀🦀🦀🦀🦀🦀🦀🦀
@TK-fo5xl
@TK-fo5xl 3 місяці тому
Would anyone explain why the code at 04:00 is dangerous?
@U20E0
@U20E0 2 місяці тому
A bad UTF-8 parser could do something wrong if given this input, but that has nothing to do with the string itself, or even with C for that matter. this is not a good example.
@TK-fo5xl
@TK-fo5xl 2 місяці тому
@@U20E0 Thanks!!
@AllanSavolainen
@AllanSavolainen 7 місяців тому
I thought you can have almost all of those on C too? And I wouldn't call char[] a string, it is just pile of chars. There are plenty of string types for C available.
@krunkle5136
@krunkle5136 7 місяців тому
C also has libraries.
@ABaumstumpf
@ABaumstumpf 7 місяців тому
So if you do not use even the basic tools that C gives you and instead write crappy code than C is dangerous - ok. C has many ways of representing string. And the standard says a string is a character-sequence terminated by a \0 character. Not an array, not a pointer, but the actual memory holding the information. so 'const char * myStr = "my string";' - myStr is not a string but a pointer to the first element of the string. And when you need to manipulate strings there are many libraries with strings for whatever usecase you have. Forcing UTF8 like Rust does it makes the language less flexible, less compatible, and basically completely impossible to use on certain systems. And aside from that it means that the native strings can not be used on many smaller systems like micro-controllers as they are just too restrictive and too memory intensive (while also not benefiting from specialised hardware). Rust just has more of these convenience types in the core language, but also a way more overloaded and error-prone set of types and functions on those types. The compiler does a lot of work for them and will tell you your errors - and there will be many. But once done you can be reasonably sure that you have removed most bugs.
@professornumbskull5555
@professornumbskull5555 7 місяців тому
0:09 PathBuf has single f
@vizigr0u
@vizigr0u 3 місяці тому
I've never heard the word Shtring so many times
@lowlevelcodingch
@lowlevelcodingch Місяць тому
i still use a type called "Charray" for my language, pretty simple, char ray/array
@m4rt_
@m4rt_ 7 місяців тому
Rc :)
@bionic_batman
@bionic_batman 5 місяців тому
Nice, didn't expect to see Hello World being written in Ukrainian
@iusearch
@iusearch 7 місяців тому
Great video, not a big fan of the white bar after 18 mins. I was flashbanged at night
@letsgetrusty
@letsgetrusty 7 місяців тому
Yeah my bad
@TheRealMangoDev
@TheRealMangoDev 7 місяців тому
&str == char*. String == Vec. EZ (jk i dont think its that easy)
The Rust Survival Guide
12:34
Let's Get Rusty
Переглядів 122 тис.
All Rust features explained
21:30
Let's Get Rusty
Переглядів 272 тис.
Why i think C++ is better than rust
32:48
ThePrimeTime
Переглядів 259 тис.
rust runs on EVERYTHING (no operating system, just Rust)
18:10
Low Level Learning
Переглядів 334 тис.
Unix Domain Socket in 100 seconds
1:41
nixhero
Переглядів 50 тис.
Strings in Rust FINALLY EXPLAINED!
21:40
Let's Get Rusty
Переглядів 73 тис.
Rust is easy... (we make it hard)
10:11
Let's Get Rusty
Переглядів 113 тис.
WHY IS THE STACK SO FAST?
13:46
Core Dumped
Переглядів 124 тис.
I spent six months rewriting everything in Rust
15:11
chris biscardi
Переглядів 381 тис.
The Truth about Rust/WebAssembly Performance
29:47
Greg Johnston
Переглядів 167 тис.
The ultimate Rust IDE is here
6:53
Let's Get Rusty
Переглядів 124 тис.
Rust Modules - Explained Like I'm 5
19:59
Let's Get Rusty
Переглядів 66 тис.
How about that uh?😎 #sneakers #airpods
0:13
Side Sphere
Переглядів 8 млн
Apple Event - May 7
38:22
Apple
Переглядів 6 млн
ПОЛГОДА строгого режима для Lenovo Legion 5 pro. Чем может обернуться обычный ремонт ноутбука?
31:47
ААНТ КОНТАКТ Сервис по ремонту техники в ЕКБ, СПБ
Переглядів 34 тис.
❌УШЛА ЭПОХА!🍏
0:37
Demin's Lounge
Переглядів 312 тис.
Индуктивность и дроссель.
1:00
Hi Dev! – Электроника
Переглядів 121 тис.