 Hello everyone. Welcome to my talk. Today I'm going to talk about why safe programming matters and why I would choose rust for that We will also talk about fast safe and sustainable programming with rust. I do have a sore throat. So sorry about that so My name is Deepu K. Shashidaran. I'm the co-lead of J-Hipster. I also created a nifty dashboard called K-dash for Kubernetes I'm an open-source aficionado and a polyglot developer. I work as a developer advocate at Octa with a focus on DevOps. I Also publish frequently about languages and tech on my blog. You can find it on Deepu.Teng Please do follow me on Twitter if you are interested in my content. I Have written a book about J-Hipster. If you like this talk, you might like the book as well So What is safe programming or to be more precise? What does being safe mean for a programming language or rather What does unsafe mean? So let's set the context first so that we can appreciate what rust offers So safety can be categorized into three memory safety type safety and threat safety or four If you count null safety as a separate item, you know for folks like me who come from a Java JavaScript In a memory safe language when you access a variable or an array Sorry or an item in an array you can be sure that you are indeed accessing what you meant to or are allowed to access In other words, you will not be reading or writing into the memory of another variable Or pointer by mistake regardless of what you do, you know in your program So why is this a big deal? I know doesn't all major programming language ensure this? Yes to a varying extents, you know sort of but languages are Unsafe by default. I mean some languages are unsafe by default for example C C plus plus You know in C or C plus plus you can access the memory of another variable by mistake or you can free a pointer twice That's called double free error Sometimes a program continues to use a pointer after it has been freed and that's called a free after use error or a dangling pointer I think most C C plus plus programmers already know this and doesn't need an explanation But for others were not too familiar with manual memory management There are a lot of you know these things that has to be taken care of so such behavior is categorized as undefined behavior as they are Unpredictable because they they could happen at runtime and they are unpredictable. They are probably no not testable most of the time So they they are you know, you don't know what happens when when these occurs Finally, there is also null safety. I come from a Java JavaScript background We are so used to the concept of null infamous for being the worst invention in in programming even you know as per its inventor Garbage collected languages need a concept of nothing so that a pointer can be freed when unused But it also leads to issues and pain like the null pointer exception that we are so used to in in Java for example Technically, this also falls under memory safety, but most memory safe languages still I know let you use null as a value leading to null pointer errors and a lot of lot of issues especially Null pointer is null pointer error is like a huge headache in languages like Java and and JavaScript Let's let's look at type safety in a type safe language When you access a variable you access it as the correct type of data it is told us This gives us the confidence to work on data without having to manually check for the data type During runtime whenever you use, you know, like if you have a data imagine if you have to if you have to check and Ensure the correctness of the data every time you want to use that data that that's that's going to be a Lot of announce right So memory safety is required for a language to be type safe. So a type safe language Let's us work with the data without having to worry about its type And we can be sure that when we use for example an integer that it is actually an integer or if you are using a floating point Number it is actually a floating point number. So we can be sure of that in type safe languages. That is a type safety And finally, there is a threat safety in a threat safe language You can access or modify the same memory from multiple threats at the same time without worrying about data races this is generally achieved by using mutual exclusion logs or threat synchronization, but threat synchronization is you know, it's not Not that intuitive and it could still lead to Issues or you know, it's not the most easiest thing to do There are also other issues around doing threat synchronization and stuff, but mutual exclusion logs are a quite standard way of doing this as well Threat safety is required for optimal memory and type safety. So generally languages that are memory and type safe tend to be threat safe So You may ask like why why does this why does all this safety matters, right? So let's let's explore a little bit more So memory safety Is is like one of the biggest culprit when it comes to security Vulnerabilities and security issues. So memory safety related issues are the cause of majority of security Vulnerabilities we encounter undefend behavior can be abused by a hacker to take control of You know of a program or to leak privileged information when we we saw what undefend behavior is right So whenever there is a memory safety issues like a dangling pointer or a double free error or Buffalo flow all these kind of things are undefend behaviors and an experience hacker can make use of this to create exploits So in memory safe languages if you try to access an array element out of its bound You will just crash the program with a panic order, which is predictable behavior Whereas in memory unsafe language like C or C++ when you do the same you might be gaining access to Memory that you normally shouldn't have access to so that way you can exploit and you know you can gather Information or you can gather access you can elevate privilege and all these kinds of things So this is why memory related bugs in C C plus plus systems often result in CVs and emergency patches There are also other memory unsafe behaviors in C C plus plus like accessing pointers from stacked frames that have been popped Memory that has been de-allocated. I mean accessing a memory that has been de-allocated iterator invalidation and so on Memory safe languages even I know ones that are not as good as rust still safeguards against such security issues And that's one of the biggest reason that we tend to You know use garbage collected languages for general purpose programming because of the memory safety that those languages offer If you take a stats, you know, we can see that as for Microsoft 70 percentage of all CVs They have our memory safety ones Two-thirds of all Linux kernel security vulnerabilities are also memory safety issues 60 to 70 percentage of iOS and Apple Security bugs are also memory safety issues as per an Apple study And that number is 90 percent for Android and 70 percentage percentage for Chrome so most of the popular security issues of all times are memory safety ones and you know even You know looking at the ones that have Names right like the most popular one. They're all most of them are memory memory Safety ones and of course, there is no suspense or there is no surprise that most of these You know come from CC plus plus systems. So imagine a world, you know without memory safety issues Imagine the amount of developer time saved amount of money saved amount of resources saved sometimes I wonder, you know Why do we still use CC plus plus right or more like why do we still trust humans against all available evidence to handle memory manually and This is all without taking other non-CV memory issues like memory leaks memory efficiency No, all all all sort of those kind of things into account. So all all these stats are only for Issues memory issues that lead to security vulnerabilities Wow, so that was all just from memory safety issues. So if you take an average, it's like more than 70 percentage of all the security issues in our industry is because of memory safety issues, right? Though not as notorious as memory safety threat safety is also a cause of major headache for developers and can result in security issues The best known type of concurrency attack is called a talk to attack Which is a race condition between checking a condition like a security credential and using the results talk to attacks are examples of integrity laws Both information laws and integrity laws Can be exploited and can lead to security issues. So these are the two types of issues you normally will encounter From threat safety issues like integrity laws and information laws and both can be exploited While threat safety related exploits are harder and less common than memory safety ones There are still a possibility. I mean you wouldn't hear of these that often as memory safety issues But they are still exploitable and they are still a possibility the only Good thing going for us is that these are harder to detect because these are not very predictable harder to detect So also harder to exploit but if someone manages to find a Data-raised condition in an application it can be exploited Finally, there is the type safety. So type safety issues are not as common As the other ones in terms of like no at least in type safe languages like they are harder to find But type safety issues can also lead to security issues and type safety is extremely You know important for memory safety. So if you work with the Languages that are weekly type it is possible to create It is possible to create memory safety Issues out of type safety issues. So it is still still an important So now that we understand how important programming safety is, right? Let me convince you why Rust is one of the safest languages and How it can avoid most of the security issues we normally encounter like imagine switching to a language that just You know just just avoids like 70 percentage of all the security issues that we face with the cc++ systems For those not familiar Rust is a high-level multi-paradigum language. It's ideal for functional and imperative programming It has a very modern and in my opinion the best tooling for a programming language Though it was intended as a systems programming language its advantages and flexibility has made it suitable for all sort of use cases And as a general purpose language So rust throws around some buzzwords in it dogs But they're not just marketing buzz they actually mean it with full sincerity and they actually matter a lot So let's explore some of them The safety guarantee is one of the most important aspect of rust So Rust is memory safe null safe type safe threat safe And and did I mention null safe? Yes null safe by design So you would have to go out of your way to break these guarantees using the unsafe keyboard So even in cases which you know if you're doing systems programming there there would be a lot of scenarios where you would have to know access memory manually or Manage memory manually or do some sort of unsafe programming and even in those cases when you would have to write unsafe code You are making it explicit So that issues can you know using the unsafe keyboard you would have to make it explicit in rust so that When when you encounter an issue it'll be easy for you to track it down to that specific code block because you know Where unsafe codes are you don't have to worry about Any other parts of your program which is you know safe by default So you'd have to only look at unsafe blocks or unsafe functions and see if there is an issue So it will be much more easier to manage then in work then working in a fully unsafe language like C or C plus plus Rust ensures memory safety at compile time using its innovative ownership mechanism I think ownership mechanism is one of the most innovative thing in rust And and also using the borrower checker built into the compiler the compiler Just does not allow memory unsafe code unless it is explicitly marked as unsafe in an unsafe block or unsafe function this static compile time analysis eliminates eliminates many types of memory bugs and with some more runtime checks rust guarantees memory safety so So there is no concept of null at the language level as I mentioned earlier instead rust provides The option enum which can be used to mark the presence or absence of a value so making So, you know that that makes the resulting code null safe and much easier to deal with and you will never encounter null pointer exceptions in The ownership and borrowing mechanism makes it one of the most memory efficient languages I mean most memory efficient language while avoiding pitfalls that comes with manual memory management and garbage collection So rust has the memory efficiency and speed comparable to cc plus plus and the memory safety Better than that of garbage collected languages like Java C sharp or cool So Rust is statically typed and it guarantees type safety by strict compile time checks and by guarantee memory safety This is not special as most modern languages are statically typed like like Java go, etc Rust also allows some level of dynamic typing with the dine keyword and any type when required But the powerful type inference and the compiler ensures type safety even in those cases You know even when you're trying to do dynamic typing the compiler still tries its best to ensure type safety Rust also guarantees threat safety using similar concepts. It uses for memory safety I mean the ownership and ownership mechanism and borrow check So along with providing standard library features like channels Mutex and ARC the ownership mechanism makes it impossible to cause accidental data races from a shared state This makes us confident to focus on the code and let the compiler worry about shared state between Threats, so you don't have to worry about threat synchronizations and any of any of those nonsense But my most favorite feature of Rust is hands down the zero cost obstructions So I can't stress enough. How cool this is especially if you're if you're doing a lot of functional state programming If you know, I mean if especially if you're doing a lot of functions to program If you're a developer using a high-level language like Python Java go There is something that you may not You know, you may not be consciously thinking about while writing those cool layers of abstraction that impresses your colleagues every layer every one of those layer of abstraction adds additional instruction sets and affects your affects the performance of the overall program in most cases It may not be noticeable because you know the whatever you're adding is like in microseconds or worst case milliseconds So it may not be noticeable But it is still there And we all know that imperative code is more performant than functional code right functional style code And that's due to abstractions as well. And that's why you can always hand code more performant performance code In in those languages. So whenever, you know, like if you're working with Languages like Java go or C sharp or Python Ruby or whatever and when you encounter Performance issues that is why most of the times you can hand code you can optimize you can tune you can you know Convert stuff to more imperative code. You can You know, you know, right, you know, you can rewrite iterators to for loops to increase performance and stuff stuff like that. So There are these kind of hand coding Techniques that you can use in those languages to extract more performance in very performance sensitive application Now some languages have compilers that are smart enough to convert some of those abstractions to more performant bytecode But only languages like Rust and C++ offers true zero cost abstractions Meaning you can write the code in whatever style and with whatever abstraction without having to worry about performance cost as the Compiler will always generate the most performant bytecode possible Meaning you you you cannot hand code it any better than what the compiler has done So for example, you can choose to create or use any number of abstractions to structure your program You could use loops I treat us you could do functional imperative programming and the result remains the same The compiler will produce the best possible implementation of the machine code for the use case regardless of the flavor of your You know regardless of the flavor of the code you you choose to write So in rust some of the most notable zero cost abstractions are ownership and borrowing iterators and closure APS Async await and futures unsafe blocks and the module boundary. These are the very notable zero cost abstractions in rust So here is a here's a small example To show you know what I meant with zero cost abstractions. So the example is using Java and rust So on the left side, you see the Java code In the Java in the Java version Performance drops as the abstractions increase while in rust. There is no noticeable difference though So in in in in the in the code that you see the first the first example on both is a factorial using For loop the second one is factorial using recursion. So the for loop doesn't have any abstractions It's a simple for loop. So that's the most performant version possible Especially in Java if you look at the numbers, it's the average is around 10 nanoseconds per operations Whereas when you do the same with recursion it increase the the performance drops and it is now 20 nanoseconds per operation. So the the you know, it's just doubled the time just doubled and if you try to use some inbuilt abstractions like Streams and use the reduce method then it further drops and becomes 23 nanoseconds per operation Whereas in rust the normal, you know, iterative Loop using a while loop it has an average of around 8.5 nanoseconds per operations and if you do the same in recursion It still has around the same 8.6 nanoseconds per operation and if you use inbuilt Abstraction like an iterator actually you get the best performance you get around 6.5 nanoseconds per operations. So that's that's that's incredible, right? So you can write your code in whatever way you choose and you don't have to worry about performance and and most of the times inbuilt abstractions might even provide better performance than your hand-return hand-optimized code because the the inbuilt abstractions would have some internal optimizations and boundary checks and all these kind of things that will you know give a little bit more Performance you could also hand code those but it's not required rust will do those things for you So you don't have to worry about those stuff. So to me zero cost abstractions are like the most underrated feature of rust and the personally the the like one of the best feature of rust so Rusty is also immutable by default and mutations have to be declared explicitly This along with the ability to pass by value or reference makes it super easy to write functional code without side effects So if you are a fan of functional programming, then you know rusties for you Rust also has excellent support for advanced pattern matching. So pattern matching is used extensively in rust for error handling and control flows It's also used extensively in standard libraries and stuff and You would see that everywhere in rust style guides rust examples documentation and so Rust also has advanced generics and traits with type aliasing and type inference support. It has great type inference Rust generics are extremely powerful So powerful that sometimes Not sometimes most of the times you could easily end up with very complex generics when especially when you Combine generics with lifetimes and you know dynamic stuff It could easily become complex. Similarly rust also have also have very powerful traits with a lot of cool features like Default implementations placeholders operator overloading trade bounds compound rates and and so on So Finally, there is also support for meta programming using macros. So rust macros are like super cool that supports both declarative macros and procedural macros and and macros can be used like annotations for adding, you know stuff like Sealization desalination using the derived Annotation you could add No behavior to struts and to two attributes and stuff you could use macros as attributes you could use them use them like functions like the inbuilt println Println and format functions for example. They're all macros. So a lot of Rust standard Library stuff is macros as well. So it's quite cool It it it's basically it basically lets you you know do metaprogramming It lets you write more concise code and and write more reusable code without having to worry about generics and stuff like that It's it's not just the language features rust as one of the best compilers and the best tooling that I have That I have seen and I have experienced and and I have worked with the the JavaScript ecosystem type script and stuff JVM languages like Java, Kotlin, Scala, Groovy I have worked with Go, Python, Ruby, C-Sharp, PHP, CC++ and maybe a couple of other like Non-mainstream languages and I have not seen a compiler as good as Rust and I have not seen a tooling as good as Rust and and and and the closest in tooling Maybe would be JavaScript or Go, but yeah, it's hands down has great tooling cargo It's like it's it's super super cool And and the way you know the rust tooling From the get-go, I mean you you download rust up and you manage everything from there it installs You know rusty it installs rust dogs it installs cargo clippy everything it installs whatever you require You can manage versions using the same command you can update to different, you know stable nightly or whatever You can manage versions you can downgrade upgrade everything so it's it's really cool even it even has Inbuilt documentation so you can use rust dog offline to get Documentation for the version that you have installed so how awesome is that right so it also has great documentation One of the great one of the best documentations among programming languages as per community Agreement I would say so yeah, it also has great It has great language features great tooling great compiler great documentation and Finally it also has a great community so it has a lot of you know Really good things and and that's the reason rust has been the most loved language For six years in a row five I think five or six years in a row in in the stack overflow Survey so it has a great community, which is diverse welcoming friendly and vibrant the ecosystem is quite young But is rapidly maturing unlike many general-purpose languages which are not appropriate for some use cases due to the trade-off they make Rusty is uniquely positioned to work across the spectrum without any major disadvantage So it can be the general-purpose language for any use case from client side web assembly To web apps microservices system programming and even for Kubernetes. I mean, you know, you can use web assembly code return with rust as Kubernetes workload So in my opinion the only thing holding back trust is the maturity of the library ecosystem Which is only a matter of time to get better. I think So CC plus plus and go might be the ones to be displaced most in the short term by rust in my opinion I think Java Java script Python Ruby, you know, etc. Are safe for a long while due to their Massive presence in last-scale applications the maturity of their ecosystem and especially due to the migration cost, you know Like and of course like you don't always, you know, you don't need rust for everything I mean, so if you have a web application return in Java, it's perfectly fine You don't you don't have to use rust for that because It may not be a performance Critical thing right so in that case you don't have to use us for that so I would say yeah before that like let's also see You know the the the the other side so All this doesn't mean that you know rust is a silver bullet. So there are also some downsides There are issues like steep learning curve and the complexity But it's a closest thing to a silver bullet in my opinion. That doesn't mean I'll you know I or you should start using rust for everything For example, I still enjoy being a polyglot developer and I'm still invested in Java JavaScript and go ecosystem But if the use case requires speed and or concurrency or building system tools or CLIs, which are like, you know Performance critical then I'll be giving rust the first preference. There's there's no doubt in that. So if the use case Requires best possible performance, then yes rust and I don't think I'll ever Advice or recommend using CC plus plus when I know that there is rust for a new project, you know, like so of course migration may not be Possible, but even that is being considered. I mean given that, you know rust is Accepted a second language for the next corner. So everything is possible But I would I would personally love to see Everything in CC plus plus, you know migrated to rust because I don't see any reason to use C plus plus when there is Something like rust that offers same speed and efficiency without the the downsides So Yeah Go and Java JavaScript. They still have their own use cases and value You know, you don't need extreme performance for everything. Sometimes you need Readability and easy to write and read code. So you will go for go. Sometimes you need Stability of ecosystem maturity of libraries, then you go for Java or Seesha based on whatever Ecosystem you are in and for client-side stuff. Of course, you go with JavaScript So in my opinion rust can be the ideal general purpose language once the ecosystem etch us The the target for a high-level language and low-level languages are quite quite different and hence the features and goals differ as Rust is a high-level language and hence is human oriented But it also has performance and efficiency that puts it into closely with low-level languages and most specifically mid-level languages like C and C Plus plus so rust also scored great in a 2017 research comparing speed memory efficiency and energy efficiency of programming languages and I'm pretty sure that those numbers You know would have only become better after in the last five years Do note that there has been some criticism from different language communities for this research Especially regarding how optimized the code was when used for benchmarks That might also explain rust scoring a bit less in memory efficiency than go Since real-world examples show a different trend because rust is known to be extremely memory-efficient as well as fast and efficient because speed energy efficiency go hand-in-hand So normally a language would offer a choice between safety and speed High-level abstractions at the very best you can pick two of those for example with Java C sharp go Python Etc you get safety and high-level abstractions at the cost of a runtime overhead in terms of garbage collection or reference counting a water Whereas in CC plus plus It gives you speed and abstractions at the cost of memory safety But rust offers all three and a good developer experience and a great community as a bonus So I don't think there are any other mainstream languages, you know that that can claim that So to to to finish off You know, you won't appreciate rust unless you spend a few weeks Building something in it. That's that's how I started appreciating rust The initial steep learning curve could be frustrating or challenging depending on how you see it and what perspective you take But once past that initial steep learning curve, it's hard not to love the language After all, it's a toddler with superpowers. So that's it folks I hope the talk was worth your time and I hope I convinced you to look into rust and consider rust You know when you have your next Project that that might for the for which you might normally consider CC plus plus or go or something like that So thank you for attending. You can reach out to me via Twitter and do check out my website For more content if you like this talk, so thank you for folks Have a have a great rest of the conference. Bye