Alice Ryhl
๐ค SpeakerAppearances Over Time
Podcast Appearances
But maybe you're writing some super high performance code and you want to avoid this if.
What I would say here is that vector has two different ways of getting a value.
There's the normal bracket operator we all use for other languages, which will do the check and crash your program if you get it wrong.
But there's another function called getUnchecked.
And so if you do write vec.getUnchecked 5, then it will give you element 5 without checking the length.
And this function, like in the function signature, it says unsafe FN.
That's the function signature.
And so you can only call this function from an unsafe block.
And so all that the unsafe block lets you do is call functions marked unsafe.
So usually it will never show up in, say, a backend server.
You would have zero uses of unsafe there.
Generally, when unsafe is used, it's to add a new feature to the language.
Let's say the language didn't have a vector.
The language still has a function to allocate memory, a function to free memory, a function to read at this point or address.
then you could write struct vec the pointer is here and this is a raw pointer so it's unsafe to use the length is this the capacity is this so i might and then you can write your little api of course the fields are private so you can't access them from outside the module i mean if i could do vector length equal 20 just access the field that would be pretty bad and so
You can write your own vector API and using field privacy and good API design, you can add a vector to the language if it doesn't already exist.
And unsafe, if encapsulated properly in this kind of API that doesn't permit you to mess it up, then you can have a safe vector that you can use from safe code.
And no matter how stupid the thing you do with that vector is, it's not going to do something bad.
It's just going to crash or whatever, check the length properly.
As long as you design your API right, you can add new language features by using unsave.