Showing posts with label Rust. Show all posts
Showing posts with label Rust. Show all posts

Saturday, May 2, 2020

timetracking-rs: Tracking Hours in Rust

I worked with Technology for a long time. I created a Python script 10 years ago to manage my working hours for control, observability, backpressure purposes. Last Friday night(What a nerd thing to do, I know), I re-wrote this script into a Rust program. I always like to build my own tools, for several reasons, like make my work more productive or just because I want an excuse to do something useful for me in a language that I liked. It took me about 4h to figure out how to do this in Rust. There were 2 basic challenges with was Strings(OH I hate Strings in Rust) and working effectively with Data/Time math operations. I would 2 hours figure it out and making this work and 2 other hours refactoring the code to make it better. Overall code with Rust is pretty productive and fun however Strings and pain in the ass. So I'm using this program every day (decommission my old python script) - so this might be useful for you too. Let's get started.



Show me the code



So we have 2 Rust files here: main, time_tracking, time_utils, and model. main we have the main application which reads the configs from the main arguments vector and parses it into a model::TimeTrackingData Struct.

The model files have structs for config and time tracking math operations. time_utils use chrono and bdays in order todo the date/time math I need for the program to work. The time_tracking has the report building pretty much and calls the hours calculations.

The complete code is here: https://github.com/diegopacheco/timetracking.rs

Video


timetracking-rs from Diego Pacheco on Vimeo.


Cheers,
Diego Pacheco

Thursday, April 16, 2020

Having fun with Rust



I',m in love with Rust 💓 since 2018. Last year I spend a great amount of time architecture and designing systems with Rust and also Learning and coding. Here are some of my POCs. I've also done several posts about Rust. So this is another one, today I want to show another lick ass things you can do with Rust. No need to say that Rust is Fast and kicks ass but today I will show so cool code I was doing with Rust by coding some Euler with Rust and Java, In comparison, some stuff in Java is actually is better than rust but most of the things are better in Rust. It takes some time to get used to Rust but once you do you will see that the Compiler is just completely amazing and helps a lot. I',m coding rust with VSCode editor thanks to RLS.  One of the features I want to show you guys is called If Let and for me is a killer feature it's super cool.  So let's get started!

Talk is Cheap, Show me the code


I've been playing with Euler with Java and Rust in order to have a fair comparison with some "real" problems that are quite interesting. So I will be definitely posting more about this subject. So this is Euler #2 problem which you need to calculate the Fibonacci sequence for numbers that are EVEN and also <=4M.  In order to do it so I had to implement memoization technique otherwise, my CPU would be completely fried by now :-)

In order to do the Memoization(Also know for common mortals like us: Cache) I used a HashMap. So why Standard HashMap? There is a Sexy new HashMap implementation in Town called HashBrown(OH BOY I miss the American Brunch during this COVID-19) Which is the Google Ported implementation of C++ Swiss Table. So since Rust 1.3.6(I'm using 1.4.3 nighly by now) is part of the STD lib in Rust!



So the cool things about this code are, besides the fact I'm using the Swiss Table Cache implementation and the code its that I'm using 2 very interesting features which are the Pattern Matcher and the IF LET.  For the Pattern Matcher I',m doing recursion and it's very clean and cool as you guys can see it.

The IF LET is another killer feature so At the beginning on the Fibonacci I need to check if the number is on the cache so there is why we use the IF LET which is do a very fast and concise Small Pattern matcher and basically says check if the cache has this key called n. If the key is there give me Some valued with the variable f. Them I have code inside {} which just returns the value. This is quite handy because I dont need to write a full Pattern Matcher there and it's short and concise.

You might realize the Cache comes by parameter to the function so I play nice with Rust borrow and ownership rules and dont need to use Unsafe{}. In Java, you would probably have the cache as a private static final and do not pass the cache as a parameter to the Fibonacci function. So In order to avoid usage of Unsafe{} I made that way.

One of the many things I like with Rust is that it makes the code Obvious, No Implicits(Like I use to not appreciate in Scala), No Crazy Aspects(Like I used to not appreciate in Java/Spring) and No Magic Interceptors (Like used to not appreciate in Ruby).  One Interesting fact about Rust is that we can do a For in any range interval by doing from 0..100 for instance but we cannot do the reverse like 100..0 so in order to that work we need to do (0..100).rev().

So that's it for today, I hope you guys like it.

Cheers,
Diego Pacheco


Tuesday, March 24, 2020

Struct and Traits in Rust

Rust is not an OOP language. However, is possible to have similar behavior using Structs and traits. Traits are great because allow us to create common and interfaces and allow structure for generic coding. The struct is like a struct in C. They allow us to have Pojos and hold both data and behavior using traits.  Today I want to show you guys how we can work with struct and traits in Rust. This is another short video focusing on understanding and also you will learn somethings about macros as well.  So I hope you guys liked it, let's get started !!!



Video


struct and traits in Rust from Diego Pacheco on Vimeo.


Code



Cheers,
Diego Pacheco

Thursday, March 19, 2020

Result & Pattern Matcher in Rust

It's common in the software language community to worry about the "idiomatic" way of doing this. So what's the idiomatic or rust way to do things. It's easy to learn new languages and continue with old mindsets coming from C or Java for instance.  IMHO Readability, High Cohesion, Loosely coupling, Debugability, Good Design are super important aspects in regards to you are idiomatic or not. But being idiomatic is like following a standard and makes things easier for all engineers. For this blog post, I want to share a video I recorded on using 2 resources in Rust called Pattern Matcher and Result. These mechanisms are not unique to Rust, actually, they are functional programming concepts.  The result is also known as a Monad and you can find it in Haskel, Java, Scala,  and several other languages, with different names like Either, Maybe, Option, Optional and so on and on.  Pattern matcher is also found in lots of languages like Haskell and Scala.

Video 


Pattern Matcher & Result in Rust from Diego Pacheco on Vimeo.


Code



Cheers,
Diego Pacheco

Tuesday, March 17, 2020

Borrowing and Ownership in Rust

Rust is a pretty interesting language. I said that not because of unique performance but also because it makes you think differently. Languages that make you think differently are great even if you dont use them in production. Rust is quite unique because it does not have Runtime like Java and neither a traditional Garbage collection. Rust managed to be efficient thanks to its's smart compiler and some new rules like Borrowing and Ownership. So I recorded a quick video to explain how Borrow and Ownership work in practices. I hope you like and have fun learning Rust.  Let's get started!

Video

Rust: Borrowing and Ownership from Diego Pacheco on Vimeo.

Code



Cheers,
Diego Pacheco

Wednesday, March 11, 2020

Running a rich Microservice constellation in Kubernetes

Languages have trade-offs like any solution in tech. Microservices are great for many reasons, one of them allows the best tool for the job. Kubernetes allows us to have the same operational standards and procedures even using different languages and solutions. For this blog post, I want to show a simple project I build which is a constellation of services. There are 5 microservices, written in several languages like Scala, Java, Go, Python and Rust. The services do a pretty basic math operation like (+, - , / , *) and the Scala one does the aggregation and orchestrate the other services using a polish notation algorithm and REST calls.

The Video



Calc Services (5 Microservices Scala, Go, Rust, Python, and Java) running on K8s from Diego Pacheco on Vimeo.

The Source Code

The complete source code is here on my github.

Cheers,
Diego Pacheco

Friday, February 14, 2020

Rust 101

Rust is a kick-ass language. Many developers hate Rust because of borrowing and responsibility rules, I get it. However, these rules that make the language so appealing and much more efficient, check it out Discord use case, they migrated from Go to Rust. Today I want to show some nice things that the language offers to any engineer who wants nothing by the best performance. Rust syntax could be better? Yes, for sure. However syntax it's not what matters most. So let's get started, I made a video for us show in practice some cool stuff about Rust, I hope you like it.


Rust 101 Video



Rust 101 from Diego Pacheco on Vimeo.


Cheers,
Diego Pacheco

Saturday, January 25, 2020

Actix(Rust) it's blazing fast

I'm a performance aficionado. I always will be :-). However, performance is a tricky thing. It always depends on the use case. There are several things could affect a benchmark like:
* Hardware
* Payload size
* Kind of Operation
* Time
* Configurations / Tunings
* Warm-Up
* What the code does and how
I never like the blind discussions saying this server is always better than that server because I knew use cases are everything. Performance is important and in the cloud, it leads to other things like Scalability and Costs. Great performance allows better scalability, therefore it reduces costs because you do more with fewer resources(machines or containers).

I want to share some very simple results from a very single, narrow and dumb use case. Let's consider the turn around speed. How much overhead our architecture introduces, for this case let's consider 2 ket metrics RPS(Requests per Second) and Tail latency(p99). I run lots of systems in production using Netty(for backend). I love Netty. Netty is also used by Cassandra, Akka, and other battle-tested kick-ass solutions. However, in the last year, I got into Rust. You might want to check it out in my previous posts on Rust, like (Building a Microservice with Rust). Besides my interest, for Rust, I need to say that Netty is battle-tested and Rust still not yet but I believe it will be soon. Actix(Rust) does not stop to amaze me.

The Benchmark

Very simple benchmark running on my own machine for the 40s testing Nodes Fastest Server(Fastify), Netty and Actix. Actix is really amazing, it looks like it's the fastest server out there.



Cheers,
Diego Pacheco

Tuesday, January 14, 2020

The dark side of Rust Language

Rust is an amazing language. If you follow my blog activity and know me in person you might know I'm really invested in rust on the last +12 months and also blogging a lot about Rust. Now I want to do something different. I do not want to paint a rosy picture of Rust. I do believe trade-offs matter and you only know something true when you know the cons. There are some problems I will expose in this blog post and not related to rust only but related in fact about two other factors. A) "New" languages. Rust has +10 years however still not mainstream and I still consider it a new language. B) New Paradigm / Approach - everything you deviate from standard C/OOP you will face resistance, I saw it happens a lot with other languages like Scala and Clojure. These problems happen in rust but I want to make it absolutely clear they are not unique to rust. So Let's get started, let's start with the Good things.

The Great Things About Rust

Before talking about rust benefits you might want to talk a look into some blog posts I made about Rust.

* Rust - The Language of the future: Rich Type System, Correct and Fast
https://y4my.blogspot.com/2019/07/rust-language-of-future-rich-type.html

* Rust and Java Interoperability
https://y4my.blogspot.com/2019/09/rust-and-java-interoperability.html

* Running Rust Service in Kubernetes with only 3.5MB
https://y4my.blogspot.com/2019/09/running-rust-service-in-kubernetes-with.html

* Building a Microservice with Rust
https://y4my.blogspot.com/2020/01/building-microservice-with-rust.html

Now let's talk about Rust Language benefits:

Live: Rust is a live language. It has a community, tech events, new ideas, and libraries are flowing and popping up every single day. I would argue this is one of the most desirable properties of a language. You want to be where the innovation is happening.

Interoperability: Rust plays very well with pretty much all other languages. It's very easy to invoke this language from rust and vice versa. For this reason, rust is really great for embedded systems and IoT for instance.

Easy To Read: Rust code is obvious, it's very easy syntax and therefore very easy to read the code. The ability to easily read the code is really important for a maintenance perspective and for learning.

Functional Vein: Rust allows functional programming, you have lambdas, Optional, map, find, filter and much more. Functional programming is a really great paradigm and a modern language needs to fully embrace it or at least partially.

Memory Allocation: Rust really forces you to think about memory allocation and memory management. Most of windows bugs are related to memory allocation issues. The Windows team is also considering using Rust.

Zero Cost of Abstractions: This is another great rust capability. Several languages have great syntactical sugar and features however often using the abstractions are SLOW compared with standard features. Rust does not have this problem.

Libraries variety: Rust has a great variety of libs and ecosystems. Crates.io has over +35K libraries.

Speed: Rust is super fast. Faster than Java, Go, C++. Rust is only slow compared with C but is not really bad. Compared with high-level languages like Java, DotNet, Go, Python, Ruby - Rust is super fast and much better than these languages in sense of speed. which means: Doing less with more, saving costs(if you are running on the cloud) and better user experience.

Safe: Rust is also super Safe. As long as you dont use the "Unsafe{ }" feature.  This is one of the main advantages of Rust. The compiler is really your friends and catches a lot of things.

Web Assembly: Web Assembly is the future of the web and the implementations are in Rust. This is another very attractive point for the language.

Small Binary, Small Footprint: Rust is not a memory sucker like Java. Rust generates very small self-contained binaries which are really great for containers like Docker and Cluster managers like Kubernetes.

Great for Concurrency: Rust is also strong in concurrency, having channels, Thread Pools, and Futures. The language provides a variety of great options and good syntax for concurrent programming.

My Personal Thoughts are that coding in rust is a pleasure and makes me learn new things and write better software. However not every ting are roses in Rust - let's talk about the dark side now.

The Dark Side of Rust

Small Market: Currently there are few companies using rust. Therefore a few programmers and few job offers. I do believe the market size will increase but if you need a massive number of developers now and it cannot afford their education - Rust is not a good choice for you now!

Too Many Strings: Rust has issues with String. Rust has 6 String types. String, Str, CString, Cstr, OsString, Ostr. Wich makes it complicated and confusing. Some functions return Str and you need to convert to String. String and Str have different functions.

Slow Compilation: As you have +200 dependencies you will see compilation become super slow. Everything or almost everything is statically linked which makes compilation slow and you have lots of outdated libs in your FS.

IDE Support is not Ideal: I'm VsCode is the best option so far but it has flaws. RLS is slow and crashes often in VSCode compared with the console. RLS code completion does not work well 100% of the time.

Libraries low maturity: Several libs are incomplete and immature. Often you find poor documentation and documentation that is not up-to-date. This making uses a library always an "adventure" so you need to look at the source code. It's often not copy-paste-n-work.

Rust is not for Beginners: Concepts like Borrow and Ownership take time for you to internalize. Try calling a function 2 times with the same variable. Rust will punish you, you won't be able to compile your code. Rust requires discipline and learning. If you cannot pay this price, do not use Rust, maybe you should consider Go or even Java instead.

Rust is a great language. I believe rust will grow a lot in the new years. Documentation, library maturity, Jobs/Engineers, Tooling support issues tend to get fixed. However, Borrow and Ownership is not going away so you will be required to learn.

Cheers,
Diego Pacheco

Monday, January 13, 2020

Building a Microservice with Rust

Rust is a great language, currently was the language that I most study in 2019 and in 2020(so far). Rust has interoperability with any language pretty much. Rust is also great for containers and to run in Kubernetes. Today I want to show how to build a simple microservice. We will use Actix, Tokio-Postgress, and other libraries. We will use Postgress as our source of truth and we will run it in docker(for development sake). We also will use Barrel + some customs migration structure I created. The code will be all async and non-blocking IO. I hope you have fun, let's get started.

 Architecture


Here we have a multi-layer architecture where the business rules and rest definitions are defined on the news-contract. The SOA contract is defined at news-contract + news-service, the Structure(News) is defined at news-contract. The rest endpoint definitions + service is defined on news-service. The postgress persistence is defined at news-dao.

Code Structure

We have 5 projects, there one global workspace which is one project, the top-level one. Them we have news-contract: which is the SOA contract part, we have the News Structure used on the code.

news-dao: We have the reactive persistence code using tokio-postgres and all the CRUD operations for the News resource.

news-migrations: We are using barrel + custom logic to create tables and add data for the sake of testing.

news-service: Here we have the endpoint, service implementation and the main class with the actix-web framework being configured.

Each project has its own dependencies and thats defined by the Cargo.toml file.

We also have 2 scripts that deal with Docker containers. One to run Postgres and the other to run psql.

Migrations

Now Let's take a look at how we can do migrations(Create tables and add records into Postgres SQL).


We are connecting on the Postgres Database running on docker and creating a Vector containing all migrations and we are running this migration. Then we are doing a for all migration going through them one by one and doing a matched checking if they went well or not.

Now let's look at the next rust code, what is a migration.


I created a structure called NewsMigration where there is a new(function used to create the struct) and the method to run the migration called (run).  As you see I created a second struct called CreateTableNewsMigration and a trait implementation using(impl) inside the code I'm using the barrel and create a table structure, the barrel will generate the Postgres SQL INSERT syntax. Finally, we are running the generated script in Postress using the pg_client. You might see code here a bit odd: &news_table[..] where we are passing the reference of the String news_table and passing a slice([..]) copying the string and passing through the method.

SOA Contract

Let's take a look into one part of the Soa Contract, the Struct News.


We are defining a Struct called News and I'm using serde and serde_json in order to be able to serialize and deserialize this struct. I'm also implementing a trait called Display in order to be able to print the struct. Finally, there is a unit test ad the end of the file and I'm testing that I can print the struct.

Endpoints / Services


Here I define the HttpServer actix and I'm defining several handlers like: index, list_news, insert_news,get_news_by_id, and delete_news_by_id. The server will be running on the localhost port 8080. All information is logged using log and env_logger creates.

Now let's take a look at the endpoint.rs file where we have the rest definitions.


Here we have macros using REST operations like PUT, DELETE and GET. Each function handler is public and basically, here I'm calling the service and getting the result back from the service and serializing into a json result.


This is the service implementation, we dont have any REST or actix dependencies here. Here is the right place to implement validations, business logic, and delegate to the dao crate. All functions on the CRUD are async.

Dao

Here is where the magic happens, we have the tokio-postgress code. Let's take a look.


This is the DAO implementation. There is a method to connect on a postgress database called connect() which happens in an async and non-blocking way. There I'm showing how to do a find_by_id. Using the tokio postgress client I'm executing a query passing the SELECT query doing a WHERE by ID. In Postgress ID is handle as a UUDI so I need to convert to string thats why you see id::text=$1 and in the same line I'm passing the ID I got from parameter with &[&id]. The DAO has more functions which you can check out on the complete code in mine GitHub.

Video: Code Walkthrough + Dead Demo

Let's takes a look at the video I made with a code walkthrough and a dead demo.


Rust Microservice from Diego Pacheco on Vimeo.

Full Source Code: https://github.com/diegopacheco/rust-playground/tree/master/rust-microservice

cheers,
Diego Pacheco

Saturday, September 28, 2019

Rust and Java Interoperability

Rust does not stop for one second to amaze me. It looks like Rust was designed to talk to every other language so easily. No kidding, it's clear way Web Assembly and rust have lots in common. Java is never an easy lang to interop with. Today I will show how easily we can interop Java & Rust. In order to do so, we will need to use the Java and Rust compilers. For Java, we will not require any other lib than the standard JDK. For Rust, we will need to create a lib project in cargo and we will need to use the crate JNI. I love this feature because java does not allow low-level code on the main language. So if we need to do something low level, efficiently Rust is my first choice, not only for safety reasons but because is really fast.  Let's get started.



Cargo.Toml

First of all, we need to create a lib project in cargo. Let's look at the Cargo.toml file.


There are 3 Important things here. First of all and more importantly the *name* this will be the name of the library, well we call RUST from Java we will need to use this exactly same name. What is tricky is that when you compile the SO file won't have that name exactly, but nevertheless in Java ill need reference the name that is here, dont reference the file name.

Secondly, we need to have the dependency of JNI which will do the Java binding for us. Finally but not less important we need to define this is a library, so Rust will generate a SO file. This is done via *[lib]* directive on the cargo file.


The Rust Lib

Now we can take a look at the rust code. This code will be located at the src/ folder and will need to be named as lib.rs. So let's take a look at it.



First of all, we are letting rust know that we will be using an extern crate called JNI. Them we can do the JNI imports we need, in rust imports are done with the keyword *use*. Now we are exposing a public function called Java_HelloWorld_hello. Which is the name of the Java class + method name. Them we need to receive some parameters like the JNI env, the Class, the input(String argument) and we will return a jstring which is a string in java. As you realize we dont use the _class. However, it needs to be there, in Rust we can get rid of the un-used warnings by adding "_" in front of the variable.

Them the code is pretty easy, we are getting the input from Java and calling Rust String format macro and returning to back to java which is done via *output.into_inner()*.

Java Code 

Now let's look the Java code.



In the code above there are 2 important things. First the private static native hello function, this needs to be defined. Secondly, there is the Library loading part. Like I said before this is tricky for 2 reasons: A) Java will look in all wrong places, so we need to pass some paths. B) We should out the name of the lib, as is in cargo file, not the path not the full path.  Them on the main method we just call the method.

Java Header

We also need to generate a C, Header file for the rust lib, this can be done via command:

javac -h . HelloWorld.java

The generated code should be like:


Here we have the JNI Exports that Java need it.

Compile & Run

Now we can compile rust by doing: *cargo build* and run java, here is a script to make it all easy.



Once you run this code you will see the following output:

 ./run.sh

LD_LIBRARY_PATH=/home/diego/github/diegopacheco/rust-playground/jni-fun/target/debug/
Hello, Diego Pacheco!

The complete source code is available on my GitHub here. 

I hope you guys like it, take care. 

Cheers,
Diego Pacheco

Monday, September 23, 2019

Running Rust Service in Kubernetes with only 3.5MB

Rust is a very exciting language. Not only for system programming but also for microservices and business development. Today I will show how we can create a simple service application in rust using Iron Framework. For this blog post, we will build a rust binary and run both in Docker and Kubernetes. In order to run kubernetes locally, I will be using minikube but you can use any kind of kubernetes cluster or distribution and it should work just fine. The most amazing thing is that we can build a rust executable with only 3.5MB and a docker image with the only 3.63MB. This is super lean!



Talk is Cheap, show me the Code!

Here we go.  Behold the main.rs file.


Here we are using Iron Web Framework and also ust env utilities in order to access OS level Env variables. The server is running on the port 8080, there is a function called hello_world with revices a request from icon a returns an Iron result with a Response. Inside the function I'm defining a key, which is a simple string that represents the env var I'm looking for, in this case, called: RUST_SVC_VERSION. After that, I'm using env_var_os to check if the var is present, also using the good rust pattern matcher to see if their var is present or not. IF The var is present I will receive Some otherwise none. In the case that the var is empty I'm returning an undefined version of the app on the response otherwise I return the value of the var concatenated with the String Hello World! V:.

We need to declare an Iron dependency in Cargo.Toml file.



Now Let build our Rust application, we will use docker to build the app, we do this way. Let's take a look at release-rust.sh file.


Here we are using rust builder in order to build the binary in an optimized way. Now we can take a look at the Dockerfile.


As you can see the Dockerfile is dead simple, we just add 1 file, which is the binary we just built and we expose the port 8080. Call the binary as main CMD from Docker and that's it, folks. Let's bake this docker image doing:


Now that we build it, we just need to run it. Let's run it by doing:


As you can realize here, I'm passing an env var to docker, with version 1, feel free to change the value and see that it works.

Let's run it with Kubernetes now. Let's take a look at the deployment and service specs.


For the deployment yaml file (^^^) as you can see we are using my docker image we just built. This image is also in my docker hub, so thats why you dont need perform any craziness to run in your minikube :D


Now we have the service yaml file (^^^) keep in mind we dont want use ClusterIP in production folks this is just for development and fun.  Having this 2 specs, we can create a folder called specs and we can deploy them to kubernetes using kubectl.


After the deploy, we can expose our service via port-forwarding and then we can call it :D


In the script above I'm using kubectl to select the pod I want using selectors, a great feature from kubernetes, I'm getting the name of the pods with the app==rustapp. Them storing this result in a bash variable and calling kubectl port-forwarding on this pod. I'm binding container 8080 port to my 8080 local port. That's it, now you can just do: curl http://localhost:8080/ and you will see it works.

Here is the complete source code in my github.

Cheers,
Diego Pacheco

Wednesday, July 31, 2019

Rust - The Language of the future: Rich Type System, Correct and Fast

Learning is a chaotic process sometimes. It's like trying to fix a puzzle with 1k pieces, sometimes you don't know where you are going but you need to feel the vide and let your gut feeling drive you. Being a software engineer means that I need to learn every single day, otherwise I'm devaluing myself and also devaluing the solutions I built and therefore the customer is getting less value at the end of the day. IMHO a software engineer is like a startup that went IPO if it's sexy, healthy, awesome and doing bleeding edge stuff the stocks go up otherwise they might go down. However, for many engineers, the only way to get better in change jobs which I think is ultimately true in the IT industry, however, I would like to ask a question, What's the point to change job if you will be the same? So in order to change you need to change first. Rust language was the last language I learned so far(2019). Every time I learn a language I learn something new and that's improved my thinking and the solutions I built. I Learned Clojure in 2011 for instance, never deliver a Clojure system in production however learning Clojure was super important to improve my functional programming skills in Scala which I do have systems in production since 2011 as well. Clojure was super important to improve my design skills. I have to confess, I'm in love with Rust, not because is the lastest language I learned so far but because it introduces great things that were present in other languages like C, Java, Scala and Go but also Performance with Safety.

I need to be careful when I write the word safety. Because If you are a functional programming engineer you will think in sense of type safety, Rust has that, don't get me wrong but Rust goes beyond that because it has Extreme Performance and Extreme Memory Safety.

Memory Safety

  • Null Pointer Safety: For instance, by default, it won't let you access static global var. Rust by default won't let you change pointer variables and have multiple pointers to the same variable. 
  • Dangling Pointers: With proper context, borrowing, slices and much more.
  • Data Races: Rust provides Safe multi-thread programming model with atomics for instance.
Rust Language also has the keyword called *Unsafe* which means you are doing something that might break or introduce bugs. This is great because by default it disallows bad practices and makes easier to catch these things during a code review session. Rust compiler is your greatest friend it can catch several things for you. Rust compiler is getting faster and faster every day. Coding in Rust by default means favor immutability over mutability which is a very functional programing principal.

Garage Collection Issues

Languages like Java, Scala, Go, C#, Python have Garage Collection. These languages require more CPU and memory power(Specialty Java and Scala :D).  Garbage collectors also introduce common well know issues like No Predictability(Hard for real-time systems),  Limited Concurrency(Global Interceptor Lock - like in Ruby), Larger Code Size(VM or GC must be included), GC Pressure could be very hard(look Cassandra for instance). Rust provides abstractions for system programming with ZERO COST of abstractions. You also can call C(Extern "C") which a syntax that is simpler than C++ for instance.

Past, Present and The Future

Rust was created by Mozilla in 2010. Rust is the secret source Mozilla was with new versions of Firefox which are super faster. Now we have OS written in Rust. Even Microsoft is considering use Rust because 70% of bugs in windows are memory-related. System programing option #1 nowadays is Rust. I love Go language as well. However, Rust is becoming my number #1 option currently. Rust is also the default implementation and engine for WebAssemly and WASMER. Which is the future! WebAssembly is the Future new Docker, so we can run sandbox code anywhere safety and compile the web so we can get the performance and also write web code in any language as long as we generate web assembly. Because WASM is a binary format. Right now besides Mozilla, we also have Yelp and Dropbox using Rust intensively.

Write is Cheap, let's see some Code!

Pattern Matcher is very similar to Scala Pattern Matcher, we can see lots of flexibility.


Rust is also great for Functional Programing: It has closures, Immutability, Type Systems via Strcuts, Traits, and Generics, High Order Function and much more.



Finally, let's see Unsafe in Action, So if you don't use Unsafe block the compiler will fail and you won't get a binary to execute the code.



You can check out the code in my Rust repository on GitHub.

Cheers,
Diego Pacheco


Chuyên mục văn hoá giải trí của VnExpress

.

© 2017 www.blogthuthuatwin10.com

Tầng 5, Tòa nhà FPT Cầu Giấy, phố Duy Tân, Phường Dịch Vọng Hậu, Quận Cầu Giấy, Hà Nội
Email: nguyenanhtuan2401@gmail.com
Điện thoại: 0908 562 750 ext 4548; Liên hệ quảng cáo: 4567.