肾结石可以吃什么水果| 梦见家里好多蛇是什么预兆| 善对什么| 晚上六点是什么时辰| 男大女6岁有什么说法| 宫颈炎吃什么药最好| 为什么说啄木鸟是树的医生| 舌尖疼是什么原因| 纸老虎是什么意思| 汗管瘤用什么药能去掉| 吃完泡面吃什么解毒| ft什么意思| 蟹黄是螃蟹的什么东西| 赵丽颖的真名叫什么| 1977属什么| 咳嗽有白痰一直不好是什么原因| 杨桃是什么季节的水果| 玉米须能治什么病| 屁股里面疼是什么原因| 天下乌鸦一般黑是什么生肖| 乳腺增生吃什么药效果好| 受罪是什么意思| 部队指导员是什么级别| 现在的节气是什么| 毛鸡蛋是什么| 痛风反复发作什么原因| 消渴是什么意思| 拔牙后喝酒有什么危害| 炖羊肉放什么| 93年属什么的| dm医学上是什么意思| 经常上火口腔溃疡是什么原因| 冬阴功汤是什么味道| 宫颈糜烂是什么原因引起的| 宝宝打嗝是什么原因| 姑息性化疗什么意思| 产后吃什么水果好| 什么东西越洗越脏| 抗组胺药是什么意思| 交警支队长是什么级别| 梦见飞机是什么意思| 长智齿牙龈肿痛吃什么药| 感恩节吃什么| 腹部b超能检查出什么| dic医学上是什么意思| 皮脂腺是什么| 肝癌是什么症状| 一点小事就暴躁的人是什么病| 决心是什么意思| 睡觉睁眼睛是什么原因| 11.22什么星座| 卡路里是什么意思| 玉米属于什么类| 11是什么生肖| 欺山莫欺水是什么意思| 经常拉屎是什么原因| 张国荣属什么生肖| jdv是什么牌子| 虾仁可以炒什么菜| 散光有什么症状| 颓废是什么意思| 肋膈角锐利是什么意思| 什么时候喝牛奶效果最佳| 钢笔刻字刻什么好| 感冒吃什么消炎药效果好| 什么是毒龙| 肝不好挂什么科室| 银屑病是什么引起的| 甲状腺功能亢进吃什么药| 鼻塞吃什么药| 异父异母是什么意思| 手掌上的三条线分别代表什么| 睡眠不好用什么泡脚助于睡眠| 我国的国花是什么花| 干支是什么意思| 梦见卖鱼是什么意思| 手发抖是什么原因引起的| 老而弥坚是什么意思| 患难见真情是什么意思| 查雌激素挂什么科| 男生什么情况想种草莓| 勃不起来吃什么药| 总胆红素高是什么病| 肾结石什么不可以吃| 中性粒细胞高是什么感染| 什么是cpi| 孩子注意力不集中缺什么微量元素| 咳嗽白痰吃什么药| 口臭是什么原因引起| 天秤座和什么星座最配| 羊水少了对宝宝有什么影响| 肛门潮湿是什么情况| 胼胝体是什么意思| 男生眉毛浓黑代表什么| 170是什么尺码| 什么的去路| 为什么越睡越困越疲惫| 罗汉果是什么| 佑是什么意思| 上天的动物是什么生肖| 角化型脚气用什么药膏| 狗狗中毒了用什么办法可以解毒| 吃完泡面吃什么解毒| 吃什么补免疫力最快| 欢天喜地是什么生肖| 1129什么星座| 脖子疼吃什么药| 睡觉为什么磨牙| 舌苔黄是什么原因引起的| 静脉曲张是什么引起的| 吃什么补充酪氨酸酶| median什么意思| 消渴症是什么病| fcm是什么意思| 榴莲为什么会苦| 怀孕三个月吃什么对胎儿好| 吃什么能降铁蛋白| 枧水是什么| 鞘膜积液是什么病| 澳门用什么币种| 户口本可以干什么坏事| 丁克是什么药| 4月是什么星座| 质询是什么意思| 胃息肉是什么引起的| 什么程度算精神出轨| 为什么饿了会想吐| 公关是什么意思| 什么叫同人文| 上海市长什么级别| 手指关节疼是什么原因| 梦见木头是什么意思| 中暑什么意思| 三里屯有什么好玩的地方| fda是什么| 光屏是什么| 脚气什么样| 糖醋里脊是什么肉做的| 不完全性右束支传导阻滞是什么意思| 突然长胖很多是什么原因| 蹲久了站起来头晕是什么原因| 伽是什么意思| 小儿割包皮挂什么科| 每天经常放屁什么原因| 女人腰疼是什么妇科病| 珑字五行属什么| 沸石为什么能防止暴沸| 谢娜人气为什么那么高| 肌酐是什么意思| 梦见着大火了是什么征兆| 金花是什么意思| 舌头上火是什么原因| 喜欢紫色的人是什么性格| lemaire是什么品牌| 身披枷锁是什么生肖| 支气管炎咳嗽吃什么药| 什么是贡菜| 黑金刚是什么药| 大便很臭什么原因| 财大气粗是什么意思| 小周天是什么意思| 心烦焦虑吃什么药| 泰山山顶叫什么| 每天早上起床口苦是什么原因| 枯木逢春是什么意思| 查甲状腺挂什么科| 5.22是什么星座| 1989年是什么蛇| 经常喝藕粉有什么好处| 你害怕什么| 女生痛经有什么办法缓解| 考试吃什么早餐| 相伴是什么意思| 大腿淤青是什么原因| 风湿类风湿有什么症状表现| 无能为力是什么意思| 人造珍珠是什么材质| 唇炎看什么科室| 年岁是什么意思| 怀孕送什么礼物| 拉肚子能吃什么食物| 茵陈和什么泡水喝对肝脏最好| 孔子原名叫什么| 不停的出汗是什么原因| 手淫会导致什么疾病| 冲煞是什么意思| 书生是什么生肖| 疱疹用什么药膏最有效| 梦见别人买房子是什么预兆| 附耳是什么意思| 辟谷是什么意思| 京东自营是什么意思| 嘴唇发乌是什么原因| 转氨酶和转移酶有什么区别| 什么炒肉好吃| 甲状腺一度肿大是什么意思| 打喷嚏是什么原因| 扁平化管理是什么意思| 阴道瘙痒是什么原因| 为什么总是做梦| 正正得什么| 为什么睡觉会张嘴| 迁坟有什么讲究和忌讳| 3月23日什么星座| 翻车了是什么意思| 低压高吃什么食物好| 生完孩子可以吃什么水果| 肝不好有什么症状| 心肌损伤是什么意思| 霉菌阴道炎是什么引起的| 荷花指什么生肖| 烂漫什么意思| 眼睛浮肿什么原因| 为什么会做春梦| 调教什么意思| 张学友和张家辉什么关系| 属龙的今年要注意什么| 锁水是什么意思| 烧烤用什么油| 被蜱虫咬了有什么症状| 什么叫糖化血红蛋白| 1835年属什么生肖| 哟西哟西什么意思| 慢性病卡有什么用| 肺炎支原体抗体阳性是什么意思| 儿童经常流鼻血什么原因造成的| 尿黄是什么病| 梦见小鬼是什么预兆| 黄色鞋子配什么颜色裤子| 善罢甘休的意思是什么| pp材质是什么材料| 为什么会胃胀气| 抑郁状态和抑郁症有什么区别| 艾滋病初期皮疹是什么样的| 心病是什么病有哪些症状| 黑皮肤适合穿什么颜色的衣服| 朱日和是什么意思| 面部提升做什么项目最好| 双非是什么| 琳五行属什么| 带状疱疹什么不能吃| 50而知天命什么意思| 天使轮是什么意思| 半路杀出个程咬金是什么意思| 放我一个人生活是什么歌| 尿泡多是什么原因| 吹空调感冒咳嗽吃什么药| 柠檬加蜂蜜泡水喝有什么功效| 夹腿综合症是什么| 水生什么五行| 脱落细胞学检查是什么| 阴间是什么意思| 白电油对人体有什么危害| 寄生茶在什么树上最好| 抱恙是什么意思| 牛子什么意思| 泌尿系统感染挂什么科| 滔滔不绝的绝什么意思| 头部MRI检查是什么意思| 政治庇护是什么意思| 想留不能留才最寂寞是什么歌| 布蕾是什么| 依托是什么意思| 梦到喝酒是什么意思| 百度

《天天爱庄园》绿色度测评报告

百度   卡门丽奇  他们帮派认识中国线人,垄断了几乎整个东区的干妈交易,噢,天呐,这已经是这个月第十场战斗了,老哥,不说了,我先去了。

The syntax of Rust is the set of rules defining how a Rust program is written and compiled.

A snippet of Rust code

Rust's syntax is similar to that of C and C++,[1][2] although many of its features were influenced by functional programming languages such as OCaml.[3]

Basics

edit

Although Rust syntax is heavily influenced by the syntaxes of C and C++, the syntax of Rust is far more distinct from C++ syntax than Java or C#, as those languages have more C-style declarations, primitive names, and keywords.

Below is a "Hello, World!" program in Rust. The fn keyword denotes a function, and the println! macro (see § Macros) prints the message to standard output.[4] Statements in Rust are separated by semicolons.

fn main() {
    println!("Hello, World!");
}

Reserved words

edit

Keywords

edit

The following words are reserved, and may not be used as identifiers:

  • as
  • async
  • await
  • break
  • const
  • continue
  • crate
  • dyn
  • else
  • enum
  • extern
  • false
  • fn
  • for
  • if
  • impl
  • in
  • let
  • loop
  • match
  • mod
  • move
  • mut
  • pub
  • ref
  • return
  • Self
  • self
  • static
  • struct
  • super
  • trait
  • true
  • type
  • union
  • unsafe
  • use
  • where
  • while

Unused words

edit

The following words are reserved as keywords, but currently have no use or purpose.

  • abstract
  • become
  • box
  • do
  • final
  • gen
  • macro
  • override
  • priv
  • try
  • typeof
  • unsized
  • virtual
  • yield

Variables

edit

Variables in Rust are defined through the let keyword.[5] The example below assigns a value to the variable with name foo and outputs its value.

fn main() {
    let foo = 10;
    println!("The value of foo is {foo}");
}

Variables are immutable by default, but adding the mut keyword allows the variable to be mutated.[6] The following example uses //, which denotes the start of a comment.[7]

fn main() {
    // This code would not compile without adding "mut".
    let mut foo = 10; 
    println!("The value of foo is {foo}");
    foo = 20;
    println!("The value of foo is {foo}");
}

Multiple let expressions can define multiple variables with the same name, known as variable shadowing. Variable shadowing allows transforming variables without having to name the variables differently.[8] The example below declares a new variable with the same name that is double the original value:

fn main() {
    let foo = 10;
    // This will output "The value of foo is 10"
    println!("The value of foo is {foo}");
    let foo = foo * 2;
    // This will output "The value of foo is 20"
    println!("The value of foo is {foo}");
}

Variable shadowing is also possible for values of different types. For example, going from a string to its length:

fn main() {
    let letters = "abc";
    let letters = letters.len();
}

Block expressions and control flow

edit

A block expression is delimited by curly brackets. When the last expression inside a block does not end with a semicolon, the block evaluates to the value of that trailing expression:[9]

fn main() {
    let x = {
        println!("this is inside the block");
        1 + 2
    };
    println!("1 + 2 = {x}");
}

Trailing expressions of function bodies are used as the return value:[10]

fn add_two(x: i32) -> i32 {
    x + 2
}

if expressions

edit

An if conditional expression executes code based on whether the given value is true. else can be used for when the value evaluates to false, and else if can be used for combining multiple expressions.[11]

fn main() {
    let x = 10;
    if x > 5 {
        println!("value is greater than five");
    }

    if x % 7 == 0 {
        println!("value is divisible by 7");
    } else if x % 5 == 0 {
        println!("value is divisible by 5");
    } else {
        println!("value is not divisible by 7 or 5");
    }
}

if and else blocks can evaluate to a value, which can then be assigned to a variable:[11]

fn main() {
    let x = 10;
    let new_x = if x % 2 == 0 { x / 2 } else { 3 * x + 1 };
    println!("{new_x}");
}

while loops

edit

while can be used to repeat a block of code while a condition is met.[12]

fn main() {
    // Iterate over all integers from 4 to 10
    let mut value = 4;
    while value <= 10 {
         println!("value = {value}");
         value += 1;
    }
}

for loops and iterators

edit

For loops in Rust loop over elements of a collection.[13] for expressions work over any iterator type.

fn main() {
    // Using `for` with range syntax for the same functionality as above
    // The syntax 4..=10 means the range from 4 to 10, up to and including 10.
    for value in 4..=10 {
        println!("value = {value}");
    }
}

In the above code, 4..=10 is a value of type Range which implements the Iterator trait. The code within the curly braces is applied to each element returned by the iterator.

Iterators can be combined with functions over iterators like map, filter, and sum. For example, the following adds up all numbers between 1 and 100 that are multiples of 3:

(1..=100).filter(|&x| x % 3 == 0).sum()

loop and break statements

edit

More generally, the loop keyword allows repeating a portion of code until a break occurs. break may optionally exit the loop with a value. In the case of nested loops, labels denoted by 'label_name can be used to break an outer loop rather than the innermost loop.[14]

fn main() {
    let value = 456;
    let mut x = 1;
    let y = loop {
        x *= 10;
        if x > value {
            break x / 10;
        }
    };
    println!("largest power of ten that is smaller than or equal to value: {y}");

    let mut up = 1;
    'outer: loop {
        let mut down = 120;
        loop {
            if up > 100 {
                break 'outer;
            }

            if down < 4 {
                break;
            }

            down /= 2;
            up += 1;
            println!("up: {up}, down: {down}");
        }
        up *= 2;
    }
}

Pattern matching

edit

The match and if let expressions can be used for pattern matching. For example, match can be used to double an optional integer value if present, and return zero otherwise:[15]

fn double(x: Option<u64>) -> u64 {
    match x {
        Some(y) => y * 2,
        None => 0,
    }
}

Equivalently, this can be written with if let and else:

fn double(x: Option<u64>) -> u64 {
    if let Some(y) = x {
        y * 2
    } else {
        0
    }
}

Types

edit

Rust is strongly typed and statically typed, meaning that the types of all variables must be known at compilation time. Assigning a value of a particular type to a differently typed variable causes a compilation error. Type inference is used to determine the type of variables if unspecified.[16]

The default integer type is i32, and the default floating point type is f64. If the type of a literal number is not explicitly provided, it is either inferred from the context or the default type is used.[17]

Primitive types

edit

Integer types in Rust are named based on the signedness and the number of bits the type takes. For example, i32 is a signed integer that takes 32 bits of storage, whereas u8 is unsigned and only takes 8 bits of storage. isize and usize take storage depending on the architecture of the computer that runs the code, for example, on computers with 32-bit architectures, both types will take up 32 bits of space.

By default, integer literals are in base-10, but different radices are supported with prefixes, for example, 0b11 for binary numbers, 0o567 for octals, and 0xDB for hexadecimals. By default, integer literals default to i32 as its type. Suffixes such as 4u32 can be used to explicitly set the type of a literal.[18] Byte literals such as b'X' are available to represent the ASCII value (as a u8) of a specific character.[19]

The Boolean type is referred to as bool which can take a value of either true or false. A char takes up 32 bits of space and represents a Unicode scalar value: a Unicode codepoint that is not a surrogate.[20] IEEE 754 floating point numbers are supported with f32 for single precision floats and f64 for double precision floats.[21]

Compound types

edit

Compound types can contain multiple values. Tuples are fixed-size lists that can contain values whose types can be different. Arrays are fixed-size lists whose values are of the same type. Expressions of the tuple and array types can be written through listing the values, and can be accessed with .index or [index]:[22]

let tuple: (u32, i64) = (3, -3);
let array: [i8; 5] = [1, 2, 3, 4, 5];
let tuple: (bool, bool) = (true, true);
let value = tuple.1; // -3
let value = array[2]; // 3

Arrays can also be constructed through copying a single value a number of times:[23]

let array2: [char; 10] = [' '; 10];

Ownership and references

edit

Rust's ownership system consists of rules that ensure memory safety without using a garbage collector. At compile time, each value must be attached to a variable called the owner of that value, and every value must have exactly one owner.[24] Values are moved between different owners through assignment or passing a value as a function parameter. Values can also be borrowed, meaning they are temporarily passed to a different function before being returned to the owner.[25] With these rules, Rust can prevent the creation and use of dangling pointers:[25][26]

fn print_string(s: String) {
    println!("{}", s);
}

fn main() {
    let s = String::from("Hello, World");
    print_string(s); // s consumed by print_string
    // s has been moved, so cannot be used any more
    // another print_string(s); would result in a compile error
}

The function print_string takes ownership over the String value passed in; Alternatively, & can be used to indicate a reference type (in &String) and to create a reference (in &s):[27]

fn print_string(s: &String) {
    println!("{}", s);
}

fn main() {
    let s = String::from("Hello, World");
    print_string(&s); // s borrowed by print_string
    print_string(&s); // s has not been consumed; we can call the function many times
}


Because of these ownership rules, Rust types are known as linear or affine types, meaning each value can be used exactly once. This enforces a form of software fault isolation as the owner of a value is solely responsible for its correctness and deallocation.[28]

When a value goes out of scope, it is dropped by running its destructor. The destructor may be programmatically defined through implementing the Drop trait. This helps manage resources such as file handles, network sockets, and locks, since when objects are dropped, the resources associated with them are closed or released automatically.[29]

Lifetimes

edit

Object lifetime refers to the period of time during which a reference is valid; that is, the time between the object creation and destruction.[30] These lifetimes are implicitly associated with all Rust reference types. While often inferred, they can also be indicated explicitly with named lifetime parameters (often denoted 'a, 'b, and so on).[31]

Lifetimes in Rust can be thought of as lexically scoped, meaning that the duration of an object lifetime is inferred from the set of locations in the source code (i.e., function, line, and column numbers) for which a variable is valid.[32] For example, a reference to a local variable has a lifetime corresponding to the block it is defined in:[32]

fn main() {
    let x = 5;                // ------------------+- Lifetime 'a
                              //                   |
    let r = &x;               // -+-- Lifetime 'b  |
                              //  |                |
    println!("r: {}", r);     //  |                |
                              //  |                |
                              // -+                |
}                             // ------------------+

The borrow checker in the Rust compiler then enforces that references are only used in the locations of the source code where the associated lifetime is valid.[33][34] In the example above, storing a reference to variable x in r is valid, as variable x has a longer lifetime ('a) than variable r ('b). However, when x has a shorter lifetime, the borrow checker would reject the program:

fn main() {
    let r;                    // ------------------+- Lifetime 'a
                              //                   |
    {                         //                   |
        let x = 5;            // -+-- Lifetime 'b  |
        r = &x; // ERROR: x does  |                |
    }           // not live long -|                |
                // enough                          |
    println!("r: {}", r);     //                   |
}                             // ------------------+

Since the lifetime of the referenced variable ('b) is shorter than the lifetime of the variable holding the reference ('a), the borrow checker errors, preventing x from being used from outside its scope.[35]

Lifetimes can be indicated using explicit lifetime parameters on function arguments. For example, the following code specifies that the reference returned by the function has the same lifetime as original (and not necessarily the same lifetime as prefix):[36]

fn remove_prefix<'a>(mut original: &'a str, prefix: &str) -> &'a str {
    if original.starts_with(prefix) {
        original = original[prefix.len()..];
    }
    original
}

In the compiler, ownership and lifetimes work together to prevent memory safety issues such as dangling pointers.[37][38]

User-defined types

edit

User-defined types are created with the struct or enum keywords. The struct keyword is used to denote a record type that groups multiple related values.[39] enums can take on different variants at runtime, with its capabilities similar to algebraic data types found in functional programming languages.[40] Both records and enum variants can contain fields with different types.[41] Alternative names, or aliases, for the same type can be defined with the type keyword.[42]

The impl keyword can define methods for a user-defined type. Data and functions are defined separately. Implementations fulfill a role similar to that of classes within other languages.[43]

Standard library

edit
Summary of Rust's types in the standard library
Type Description Examples
String UTF-8-encoded strings (dynamic)
  • String::new()
  • String::from("Hello")
  • "??????".to_string()
  • OsStr
  • OsString
Platform-native strings[note 1] (borrowed[44] and dynamic[45])
  • OsStr::new("Hello")
  • OsString::from("world")
  • Path
  • PathBuf
Paths (borrowed[46] and dynamic[47])
  • Path::new("./path/to")
  • PathBuf::from(r"C:.\path\to")
  • CStr
  • CString
C-compatible, null-terminated strings (borrowed[48] and dynamic[48])
  • c"Hello"
  • CStr::from_bytes_with_nul(b"Hello\0").unwrap()
  • CString::new("world").unwrap()
Vec<T> Dynamic arrays
  • Vec::new()
  • vec![1, 2, 3, 4, 5]
Option<T> Option type
  • None
  • Some(3)
  • Some("hello")
Result<T, E> Error handling using a result type
  • Ok(3)
  • Err("something went wrong")
Box<T> A pointer to a heap-allocated value.[48] Similar to C++'s std::unique_ptr.
let boxed: Box<u8> = Box::new(5);
let val: u8 = *boxed;
Rc<T> Reference counting pointer[49]
let five: Rc<u8> = Rc::new(5);
let also_five: Rc<u8> = five.clone();
Arc<T> Atomic, thread-safe reference counting pointer[50]
let foo: Arc<Vec<f32>> = Arc::new(vec![1.0, 2.0]);
let a: Arc<Vec<f32>> = foo.clone(); // a can be sent to another thread
Cell<T> A mutable memory location[51]
let c: Cell<u8> = Cell::new(5);
c.set(10);
Mutex<T> A mutex lock for shared data contained within.[52]
let mutex: Mutex<u32> = Mutex::new(0_u32);
let _guard: LockResult<MutexGuard<'_, u32>> = mutex.lock();
RwLock<T> Readers–writer lock[53]
let lock: RwLock<u8> = RwLock::new(5);
let r1: u8 = lock.read().unwrap();
Condvar A conditional monitor for shared data[54]
 let (lock, cvar): (Mutex<bool>, Condvar) = (Mutex::new(true), Condvar::new());
// As long as the value inside the `Mutex<bool>` is `true`, we wait.
let _guard: Mutex<bool> = cvar.wait_while(lock.lock().unwrap(), |pending| { *pending }).unwrap();
Duration Type that represents a span of time[55]
Duration::from_millis(1) // 1ms
HashMap<K, V> Hash table[56]
let mut player_stats: HashMap<String, u32> = HashMap::new();
player_stats.insert("damage", 1);
player_stats.entry("health").or_insert(100);
BTreeMap<K, V> B-tree[57]
let mut solar_distance: BTreeMap<String, f32> = BTreeMap::from([
    ("Mercury", 0.4),
    ("Venus", 0.7),
]);
solar_distance.entry("Earth").or_insert(1.0);

Option values are handled using syntactic sugar, such as the if let construction, to access the inner value (in this case, a string):[58]

fn main() {
    let name1: Option<&str> = None;
    // In this case, nothing will be printed out
    if let Some(name) = name1 {
        println!("{name}");
    }

    let name2: Option<&str> = Some("Matthew");
    // In this case, the word "Matthew" will be printed out
    if let Some(name) = name2 {
        println!("{name}");
    }
}

Pointers

edit
Summary of Rust's pointer and reference primitive types
Type Description Examples
  • &T
  • &mut T
References (immutable and mutable)
  • let x_ref: &T = &x;
  • let x_ref: &mut T = &mut x;
  • Option<&T>
  • Option<&mut T>
  • Option wrapped reference
  • Possibly null reference
  • None
  • let x_ref: Option<&T> = Some(&x);
  • let x_ref: Option<&mut T> = Some(&mut x);
  • Box<T>
  • Option<Box<T>>
A pointer to heap-allocated value

(or possibly null pointer if wrapped in option)[48]

  • let boxed: Box<u8> = Box::new(0);
  • let boxed: Option<Box<String>> = Some(Box::new("Hello World"));
  • *const T
  • *mut T
  • let x_ptr: *const T = &x as *const T;
  • let x_ptr: *mut T = &mut x as *mut T;

To prevent the use of null pointers and their dereferencing, the basic & and &mut references are guaranteed to not be null. Rust instead uses Option for this purpose: Some(T) indicates that a value is present, and None is analogous to the null pointer.[59] Option implements a "null pointer optimization", avoiding any spatial overhead for types that cannot have a null value (references or the NonZero types, for example).[60] Though null pointers are idiomatically avoided, the null pointer constant in Rust is represented by std::ptr::null().

Rust also supports raw pointer types *const and *mut, which may be null; however, it is impossible to dereference them unless the code is explicitly declared unsafe through the use of an unsafe block. Unlike dereferencing, the creation of raw pointers is allowed inside of safe Rust code.[61]

Type conversion

edit

Rust provides no implicit type conversion (coercion) between most primitive types. But, explicit type conversion (casting) can be performed using the as keyword.[62]

let x = 1000;
println!("1000 as a u16 is: {}", x as u16);
A presentation on Rust by Emily Dunham from Mozilla's Rust team (linux.conf.au conference, Hobart, 2017)

Polymorphism

edit

Generics

edit

Rust's more advanced features include the use of generic functions. A generic function is given generic parameters, which allow the same function to be applied to different variable types. This capability reduces duplicate code[63] and is known as parametric polymorphism.

The following program calculates the sum of two things, for which addition is implemented using a generic function:

use std::ops::Add;

// sum is a generic function with one type parameter, T
fn sum<T>(num1: T, num2: T) -> T
where  
    T: Add<Output = T>,  // T must implement the Add trait where addition returns another T
{
    num1 + num2  // num1 + num2 is syntactic sugar for num1.add(num2) provided by the Add trait
}

fn main() {
    let result1 = sum(10, 20);
    println!("Sum is: {}", result1); // Sum is: 30

    let result2 = sum(10.23, 20.45);
    println!("Sum is: {}", result2); // Sum is: 30.68
}

At compile time, polymorphic functions like sum are instantiated with the specific types the code requires; in this case, sum of integers and sum of floats.

Generics can be used in functions to allow implementing a behavior for different types without repeating the same code. Generic functions can be written in relation to other generics, without knowing the actual type.[64]

Traits

edit
 
Excerpt from std::io

Rust's type system supports a mechanism called traits, inspired by type classes in the Haskell language,[65] to define shared behavior between different types. For example, the Add trait can be implemented for floats and integers, which can be added; and the Display or Debug traits can be implemented for any type that can be converted to a string. Traits can be used to provide a set of common behavior for different types without knowing the actual type. This facility is known as ad hoc polymorphism.

Generic functions can constrain the generic type to implement a particular trait or traits; for example, an add_one function might require the type to implement Add. This means that a generic function can be type-checked as soon as it is defined. The implementation of generics is similar to the typical implementation of C++ templates: a separate copy of the code is generated for each instantiation. This is called monomorphization and contrasts with the type erasure scheme typically used in Java and Haskell. Type erasure is also available via the keyword dyn (short for dynamic).[66] Because monomorphization duplicates the code for each type used, it can result in more optimized code for specific-use cases, but compile time and size of the output binary are also increased.[67]

In addition to defining methods for a user-defined type, the impl keyword can be used to implement a trait for a type.[43] Traits can provide additional derived methods when implemented.[68] For example, the trait Iterator requires that the next method be defined for the type. Once the next method is defined, the trait can provide common functional helper methods over the iterator, such as map or filter.[69]

Trait objects

edit

Rust traits are implemented using static dispatch, meaning that the type of all values is known at compile time; however, Rust also uses a feature known as trait objects to accomplish dynamic dispatch, a type of polymorphism where the implementation of a polymorphic operation is chosen at runtime. This allows for behavior similar to duck typing, where all data types that implement a given trait can be treated as functionally equivalent.[70] Trait objects are declared using the syntax dyn Tr where Tr is a trait. Trait objects are dynamically sized, therefore they must be put behind a pointer, such as Box.[71] The following example creates a list of objects where each object can be printed out using the Display trait:

use std::fmt::Display;

let v: Vec<Box<dyn Display>> = vec![
    Box::new(3),
    Box::new(5.0),
    Box::new("hi"),
];

for x in v {
    println!("{x}");
}

If an element in the list does not implement the Display trait, it will cause a compile-time error.[72]

Memory safety

edit

Rust is designed to be memory safe. It does not permit null pointers, dangling pointers, or data races.[73][74][75][76] Data values can be initialized only through a fixed set of forms, all of which require their inputs to be already initialized.[77]

Unsafe code can subvert some of these restrictions, using the unsafe keyword.[61] Unsafe code may also be used for low-level functionality, such as volatile memory access, architecture-specific intrinsics, type punning, and inline assembly.[78]

Memory management

edit

Rust does not use garbage collection. Memory and other resources are instead managed through the "resource acquisition is initialization" convention,[79] with optional reference counting. Rust provides deterministic management of resources, with very low overhead.[80] Values are allocated on the stack by default, and all dynamic allocations must be explicit.[81]

The built-in reference types using the & symbol do not involve run-time reference counting. The safety and validity of the underlying pointers is verified at compile time, preventing dangling pointers and other forms of undefined behavior.[82] Rust's type system separates shared, immutable references of the form &T from unique, mutable references of the form &mut T. A mutable reference can be coerced to an immutable reference, but not vice versa.[83]

Macros

edit

Macros allow generation and transformation of Rust code to reduce repetition. Macros come in two forms, with declarative macros defined through macro_rules!, and procedural macros, which are defined in separate crates.[84][85]

Declarative macros

edit

A declarative macro (also called a "macro by example") is a macro, defined using the macro_rules! keyword, that uses pattern matching to determine its expansion.[86][87] Below is an example that sums over all its arguments:

macro_rules! sum {
    ( $initial:expr $(, $expr:expr )* $(,)? ) => {
        $initial $(+ $expr)*
    }
}

fn main() {
    let x = sum!(1, 2, 3);
    println!("{x}"); // prints 6
}

Procedural macros

edit

Procedural macros are Rust functions that run and modify the compiler's input token stream, before any other components are compiled. They are generally more flexible than declarative macros, but are more difficult to maintain due to their complexity.[88][89]

Procedural macros come in three flavors:

  • Function-like macros custom!(...)
  • Derive macros #[derive(CustomDerive)]
  • Attribute macros #[custom_attribute]

Interface with C and C++

edit

Rust has a foreign function interface (FFI) that can be used both to call code written in languages such as C from Rust and to call Rust code from those languages. As of 2024, an external library called CXX exists for calling to or from C++.[90] Rust and C differ in how they lay out structs in memory, so Rust structs may be given a #[repr(C)] attribute, forcing the same layout as the equivalent C struct.[91]

See also

edit

Notes

edit
  1. ^ On Unix systems, this is often UTF-8 strings without an internal 0 byte. On Windows, this is UTF-16 strings without an internal 0 byte. Unlike these, str and String are always valid UTF-8 and can contain internal zeros.

References

edit
  1. ^ Proven, Liam (2025-08-07). "Rebecca Rumbul named new CEO of The Rust Foundation". The Register. Archived from the original on 2025-08-07. Retrieved 2025-08-07. Both are curly bracket languages, with C-like syntax that makes them unintimidating for C programmers.
  2. ^ Vigliarolo, Brandon (2025-08-07). "The Rust programming language now has its own independent foundation". TechRepublic. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  3. ^ Klabnik & Nichols 2019, p. 263.
  4. ^ Klabnik & Nichols 2019, pp. 5–6.
  5. ^ Klabnik & Nichols 2023, p. 32.
  6. ^ Klabnik & Nichols 2023, pp. 32–33.
  7. ^ Klabnik & Nichols 2023, pp. 49–50.
  8. ^ Klabnik & Nichols 2023, pp. 34–36.
  9. ^ Klabnik & Nichols 2023, pp. 6, 47, 53.
  10. ^ Klabnik & Nichols 2023, pp. 47–48.
  11. ^ a b Klabnik & Nichols 2023, pp. 50–53.
  12. ^ Klabnik & Nichols 2023, p. 56.
  13. ^ Klabnik & Nichols 2023, pp. 57–58.
  14. ^ Klabnik & Nichols 2023, pp. 54–56.
  15. ^ Klabnik & Nichols 2019, pp. 104–109.
  16. ^ Klabnik & Nichols 2019, pp. 24.
  17. ^ Klabnik & Nichols 2019, pp. 36–38.
  18. ^ Klabnik & Nichols 2023, pp. 36–38.
  19. ^ Klabnik & Nichols 2023, p. 502.
  20. ^ "Glossary of Unicode Terms". Unicode Consortium. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  21. ^ Klabnik & Nichols 2019, pp. 38–40.
  22. ^ Klabnik & Nichols 2023, pp. 40–42.
  23. ^ Klabnik & Nichols 2023, p. 42.
  24. ^ Klabnik & Nichols 2019, pp. 59–61.
  25. ^ a b Klabnik & Nichols 2019, pp. 63–68.
  26. ^ Klabnik & Nichols 2019, pp. 74–75.
  27. ^ Klabnik & Nichols 2023, pp. 71–72.
  28. ^ Balasubramanian, Abhiram; Baranowski, Marek S.; Burtsev, Anton; Panda, Aurojit; Rakamari?, Zvonimir; Ryzhyk, Leonid (2025-08-07). "System Programming in Rust". Proceedings of the 16th Workshop on Hot Topics in Operating Systems. HotOS '17. New York, NY, US: Association for Computing Machinery. pp. 156–161. doi:10.1145/3102980.3103006. ISBN 978-1-4503-5068-6. S2CID 24100599. Archived from the original on June 11, 2022. Retrieved June 1, 2022.
  29. ^ Klabnik & Nichols 2023, pp. 327–30.
  30. ^ "Lifetimes". Rust by Example. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  31. ^ "Explicit annotation". Rust by Example. Retrieved 2025-08-07.
  32. ^ a b Klabnik & Nichols 2019, p. 194.
  33. ^ Klabnik & Nichols 2019, pp. 75, 134.
  34. ^ Shamrell-Harrington, Nell (2025-08-07). "The Rust Borrow Checker – a Deep Dive". InfoQ. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  35. ^ Klabnik & Nichols 2019, pp. 194–195.
  36. ^ Klabnik & Nichols 2023, pp. 208–12.
  37. ^ Klabnik & Nichols 2023, 4.2. References and Borrowing.
  38. ^ Pearce, David (17 April 2021). "A Lightweight Formalism for Reference Lifetimes and Borrowing in Rust". ACM Transactions on Programming Languages and Systems. 43: 1–73. doi:10.1145/3443420. Archived from the original on 15 April 2024. Retrieved 11 December 2024.
  39. ^ Klabnik & Nichols 2019, p. 83.
  40. ^ Klabnik & Nichols 2019, p. 97.
  41. ^ Klabnik & Nichols 2019, pp. 98–101.
  42. ^ Klabnik & Nichols 2019, pp. 438–440.
  43. ^ a b Klabnik & Nichols 2019, pp. 93.
  44. ^ "OsStr in std::ffi". The Rust Standard Library documentation. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  45. ^ "OsString in std::ffi". The Rust Standard Library documentation. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  46. ^ "Path in std::path". The Rust Standard Library documentation. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  47. ^ "PathBuf in std::path". The Rust Standard Library documentation. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  48. ^ a b c d "std::boxed". The Rust Standard Library documentation. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  49. ^ "Rc in std::rc". The Rust Standard Library documentation. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  50. ^ "Arc in std::sync". The Rust Standard Library documentation. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  51. ^ "Cell in std::cell". The Rust Standard Library documentation. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  52. ^ "Mutex in std::sync". The Rust Standard Library documentation. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  53. ^ "RwLock in std::sync". The Rust Standard Library documentation. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  54. ^ "Condvar in std::sync". The Rust Standard Library documentation. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  55. ^ "Duration in std::time". The Rust Standard Library documentation. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  56. ^ "HashMap in std::collections". The Rust Standard Library documentation. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  57. ^ "BTreeMap in std::collections". The Rust Standard Library documentation. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  58. ^ McNamara 2021.
  59. ^ Klabnik & Nichols 2019, pp. 101–104.
  60. ^ "std::option". The Rust Standard Library documentation. Retrieved 2025-08-07.
  61. ^ a b Klabnik & Nichols 2019, pp. 418–427.
  62. ^ "Casting". Rust by Example. Retrieved 2025-08-07.
  63. ^ Klabnik & Nichols 2019, pp. 171–172.
  64. ^ Klabnik & Nichols 2019, pp. 171–172, 205.
  65. ^ "Influences". The Rust Reference. Archived from the original on November 26, 2023. Retrieved December 31, 2023.
  66. ^ Klabnik & Nichols 2019, pp. 181, 182.
  67. ^ Gjengset 2021, p. 25.
  68. ^ Klabnik & Nichols 2019, pp. 182–184.
  69. ^ Klabnik & Nichols 2019, pp. 281–283.
  70. ^ Klabnik & Nichols 2023, 18.2. Using Trait Objects That Allow for Values of Different Types.
  71. ^ Klabnik & Nichols 2019, pp. 441–442.
  72. ^ Klabnik & Nichols 2019, pp. 379–380.
  73. ^ Rosenblatt, Seth (2025-08-07). "Samsung joins Mozilla's quest for Rust". CNET. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  74. ^ Brown, Neil (2025-08-07). "A taste of Rust". LWN.net. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  75. ^ "Races". The Rustonomicon. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  76. ^ Vandervelden, Thibaut; De Smet, Ruben; Deac, Diana; Steenhaut, Kris; Braeken, An (7 September 2024). "Overview of Embedded Rust Operating Systems and Frameworks". Sensors. 24 (17): 5818. Bibcode:2024Senso..24.5818V. doi:10.3390/s24175818. PMC 11398098. PMID 39275729.
  77. ^ "The Rust Language FAQ". The Rust Programming Language. 2015. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  78. ^ McNamara 2021, p. 139, 376–379, 395.
  79. ^ "RAII". Rust by Example. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  80. ^ "Abstraction without overhead: traits in Rust". Rust Blog. Archived from the original on September 23, 2021. Retrieved October 19, 2021.
  81. ^ "Box, stack and heap". Rust by Example. Archived from the original on 2025-08-07. Retrieved 2025-08-07.
  82. ^ Klabnik & Nichols 2019, pp. 70–75.
  83. ^ Klabnik & Nichols 2019, p. 323.
  84. ^ Klabnik & Nichols 2023, pp. 449–455.
  85. ^ Gjengset 2021, pp. 101–102.
  86. ^ "Macros By Example". The Rust Reference. Archived from the original on 2025-08-07. Retrieved 21 April 2023.
  87. ^ Klabnik & Nichols 2019, pp. 446–448.
  88. ^ "Procedural Macros". The Rust Programming Language Reference. Archived from the original on 7 November 2020. Retrieved 23 Mar 2021.
  89. ^ Klabnik & Nichols 2019, pp. 449–455.
  90. ^ "Safe Interoperability between Rust and C++ with CXX". InfoQ. 2025-08-07. Archived from the original on January 22, 2021. Retrieved 2025-08-07.
  91. ^ "Type layout". The Rust Reference. Archived from the original on 2025-08-07. Retrieved 15 July 2022.

Sources

edit
粘液阳性是什么意思 艾灰有什么作用和功效 吃的少还胖什么原因 九月29号是什么星座 跌打损伤挂什么科
荡漾什么意思 紫砂壶泡什么茶最好 ccb是什么药物 生脉饮适合什么人群 淼怎么读什么意思
吃什么才能减肥 死板是什么意思 什么预警停课 西红柿生吃有什么好处 喝豆腐脑有什么好处和坏处
什么牌子的蜂蜜比较好 泡汤是什么意思 增加胃动力最好的药是什么药 明天是什么 月经崩漏吃什么止血
饕餮什么意思hcv8jop6ns0r.cn 菊花和什么一起泡最好hcv9jop1ns9r.cn 前庭神经炎吃什么药hcv8jop9ns6r.cn 性无能是什么意思hcv9jop1ns3r.cn 什么叫贵妃镯hcv8jop9ns6r.cn
狗皮膏药是什么意思hcv7jop5ns3r.cn 骨密度z值是什么意思xianpinbao.com 小肚子疼是什么原因女性hcv8jop6ns6r.cn 黄精吃了有什么好处hcv9jop3ns8r.cn hpv病毒是什么原因引起的hcv8jop2ns8r.cn
上面日下面立读什么hcv9jop1ns4r.cn 失去抚养权意味着什么hcv9jop1ns2r.cn 什么是天葬onlinewuye.com 离歌是什么意思hcv9jop3ns5r.cn lava是什么意思hcv8jop3ns5r.cn
月经周期是什么意思hcv9jop0ns1r.cn 点到为止是什么意思hcv8jop6ns0r.cn 辣木籽有什么功效hcv8jop0ns5r.cn 立秋是什么意思hcv9jop6ns7r.cn 怀孕后不能吃什么hcv7jop5ns6r.cn
百度