
Rust, a programming language for Luddites
Developed by Mozilla to write Servo, a possible successor to Firefox, it uses LLVM in the backend... and a hard front-end coder.
Rust's code is available on Githube, the language is of interest to programmers who see it as a possible successor to C++ in their field.
The word "rust" in ancient English means red and may be an allusion to the fox, the symbol of Mozilla. It is also the name of a fungus (we think of a hallucinogen).
Rust is not a new C, to which dynamic arrays, objects, a mattern mixing different types, automatic memory management, as Vala did, would be added.
Its main advantage is the security of memory management, it also repeats old principles with new reserve words and syntax, which is probably more expressive when you only manage to read it. He seems to be trying to be different for principle, not efficiency.
Here's "Cathedral and Bazaar" author Eric Raymond's take on Rust:
Even the most simplistic things like concatenating two lines of characters are unreasonably difficult. Language requires a lot of fuzzy and dark ritual before you can get anything.
It is clear that the creators of the language are very far from ludifying the work, but rather tend to be Luddite. It would be better if security was achieved through a more developed backend (see Erlang) than through increased coding work.
How the compiler works
The steps for creating an executable program are described in the following diagram:
The scanner and then the parser produce the AST code (Abstract Syntax Tree). This code is being optimized.
Semantic analysis is then performed, which performs multiple checks. The 2016 version of the compiler does this in two steps: creates high-level intermediate code and then medium-level intermediate code.
The next step is to generate LLVM code, which is made from MIR and in combination with the LLVM API. There is a choice: Create a bitcode or assembler or object code. In the latter case, the LLVM link editor produces platform-specific executable code.
Language syntax
Compare the basic elements of Rust with those of C or C++ or the language modernizing these new elements that occur in all the latter languages.
Rust
fn main() {
println!("Hello World!");
}
C
void main() {
puts("Hello World!");
}
Displays a string variable.
Rust
let str = "pourquoi ne pas faire compliqué";
println!("str: {}", str);
C
char *str = "quand on pourrait faire simple";
puts(str);
Rust
let alpha: String = "Beta".to_string();
C
char *alpha = "Beta"
In Rust, all local variables are declared by let and are constant! You need to add a mut declarator to assign them again...
Default variable in Rust
let a = 1;
a += 1; // Erreur!
Constant C
const int a = 1;
a += 1; // Erreur!
The "variable to change" in Rust is a variable (like the name) in C!!!
Variable Rust
let mut b = 2;
b += 1; // Ok
Variable C
int b = 2;
b += 1; // Ok
The type is determined by the conclusions, but since this can be ambiguous (and therefore not for sure, it should be noted), the possibility of an optional explicit statement was added. The forced nature of the language would like this to be the default syntax.
Explicit Rust types
let b : int = 2;
let ch : char = 'x';
Explicit C types
int b = 2;
char ch = 'x';
Tuples - mixed lists. Same picture.
Motorcade in Rust
let t = (4, 5.0, false, "hello");
Mixed table in modern language
array t = [ 4, 5.0, false, "hello"]
The switchboard structure is renamed to match to do more. The main thing is that it is more developed, like in the Rock.
Match in Rust
let x : int = 1;
match x {
0 => { println!("Non trouvé"); }
1 => { println!("Trouvé"); }
_ => { println!("Défaut"); } // par défaut
}
Switch in C
int x = 1;
switch(x) {
case 0: puts("Non trouvé"); break;
case 1: puts("Trouvé"); break;
default:
println!("Par défaut");
}
The loop for inspired Python is the only case when Rust is simpler than C. The first versions of the language wrote: for i in range (0, 10). Then it turned out that the syntax of the Script language was the best.
Rust
for i in 0..10 {
...
}
C
for(i = 0; i <= 10; i++) {
...
}
Rust utilise une structure spéciale pour les boucles sans limite définie. Pas indispensable.
Rust
let ctr = 0;
loop {
ctr += 1;
if(ctr == 1) {
break;
}
}
C
#define forever 1
int ctr = 0;
while(forever) {
ctr += 1;
if(ctr == 1) {
break;
}
}
La déclaration d'une fonction montre bien l'aspect verlan de Rust par rapport à C! En-tête plus compliquée sans raison, retour plus simple mais inutilement moins sûr, ou est la cohérence?
Rust
fn mult(x: int, y: int) -> int {
x * y
}
C
int mult(int x, int y) {
return (x * y);
}
Lecture des lignes d'un fichier une à une...
Rust
let filename = "myfile.txt";
let f = try!(File::open(filename));
let mut file = BufReader::new(&f);
for x in file.lines() {
let line = x.unwrap();
println!("{}", line);
}
C++
char *filename = "myfile.txt";
string line;
ifstream file(filename);
while(getline(file, line)){
cout << line << endl;
}
Les struct servent de classes mais les méthodes sont déclarées séparément, ce qui est une option en C++.
Struct en Rust
struct Point {
x: int,
y: int,
}
impl Point {
fn Start() -> Point {
Point { x: 0, y: 0 }
}
}
Class en C++
class Point {
int x;
int y;
Point Start() {
x = 0;
y = 0;
return this;
}
}
En conclusion, Rust a été conçu comme langage système pour remplacer C++ avec une gestion mémoire plus sûre, un point qu'on ne lui disputera pas. Etait-il nécessaire pour parvenir à ce résultat de changer la syntaxe et la rendre inutilement obscure? Les motivations des auteurs ne sont pas claires, car les défauts de C, à savoir les points-virgules (une erreur selon les auteurs de C eux-mêmes) sont conservés, mais la simplicité des déclarations ne l'est pas.
Les possibilités des éléments du langage ont aussi été restreintes pour réduire le risque d'erreurs. C'est quelque chose qui n'a pas réussi dans le passé à Pascal ou Modula.
Faut-il utiliser Rust?
Faut-il utiliser Rust, donc le choisir plutôt que Go ou C++? On mettra go de coté car il est plutôt en compétition avec les langages de serveurs comme Java, Python, PHP, un garbage collector peut être un inconvénienr, et son système de modules en ligne l'est encore plus, ainsi que l'absence de généricité.
Reste donc à choisir entre l'insécurité de C++ quand il est mal programmé, mais avec une liberté totale et la possibilité de réaliser ce que l'on veut, ou faire avec la syntaxe obscure de Rust pour une gestion mémoire plus sûre. Il y a de nombreuses raisons de rester en C++: des tonnes de bibliothèques, tous les outils de développements utiles, la vitesse d'exécution.
Référence : Manual de référence Rust (Anglais).