# Rust

Rust是我一直想了解的语言；唯一的障碍可能就是即使会了一些Rust，短期内看不到哪里能够实际用上。然而学习一门新东西，并不总能立刻看到用途的。

## 入门

### 安装和运行

• 异常丝滑，这是传统C/C++生态圈无法比拟的。
• Hello world可执行文件只有几兆，匹敌所有编译语言。
• 所有依赖统一由Cargo管理，不存在找不到的问题。
• Cargo自带了编译和运行功能，相当于集成了Make。

### Core features

• Rust has a strong, static type system. However, it also has type inference. Every type must be known at compile time.
• Rust allows shadowing of variables.
• Ownership is a key concept to the language.
• Each value in Rust has a variable that’s called its owner.
• There can only be one owner at a time.
• When the owner goes out of scope, the value will be dropped.
• Zero-based indexing.
• In function signatures, you must declare the type of each parameter.
• Distinguished expression and statement.
• Rust will never automatically create “deep” copies of data.
• References (&) refer to some value without taking ownership of it.
• At any given time, you can have either one mutable reference or any number of immutable references.
• References must always be valid.
• Rust deliberately avoids the concept of null for safety.
• Traits are Rust’s way of doing generic programming.
• Matches are exhaustive: we must exhaust every last possibility in order for that code to be valid.
• Iterators
• Closures
• Automatic referencing and dereferencing, so the equivalent of -> operator in C++ is not needed.
• Elision rules:
1. Each parameter that is a reference gets its own lifetime parameter.
2. If there is exactly one input lifetime parameters, that lifetime is assigned to all output lifetime parameters.
3. If there are multiple input lifetime parameters, but one of them is &self or &mut self because this is a method, the lifetime of self is assgiend to all output lifetime parameters.
• All whitespaces, no tags.
• Whitespace between curly braces.
• Opening curly brace on the same line.
• All uppercase with underscores between words for constants.
• Snake case for function and variable names.
• Specify the parent module when calling the function to make it clear that the function isn’t locally defined.
• Specify the full path when bringing in structs, enums, and other items with use.
• CamelCase for types.

## 个人体验

Rust的type inference和Julia的师出同门，和C++的auto也类似。而更进一步，Rust中绝大部分时候变量的lifetime也是inferred,而Julia中是garbage collected，C++中则全是程序员的责任。在某些情况下，Rust compiler需要程序员帮忙才能分析出输入输出的lifetime，这就引入了大部分别的语言没有的lifetime annotations。

Rust的出现并不是要你去用它重写一切，而是希望你可以用它创造新的未来。 We choose to use Rust, not because it is easy, but because it is hard, because that goal will serve to organize and measure the best of our energies and skills, because that challenge is one that we are willing to accept, one we are unwilling to postpone, and one which we intend to win, and the others, too.

Tags:

Categories:

Updated: