Rust语言基础语法

本文介绍了Rust语言的基础概念,包括如何让程序运行、常量和变量的区别、数据类型、条件判断(if和match)、以及循环语句(无条件loop、while和for)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


Rust程序设计语言-官方文档

一、让程序跑起来

使用cargo创建一个项目,输出hello,world!

$cargo new hello

# hello.rs
fn main() {
   
    println!("Hello, world!");
}
------------------
$cargo run hello
   Compiling hello v0.1.0 (D:\RustPro\hello)
    Finished dev [unoptimized + debuginfo] target(s) in 1.39s
     Running `target\debug\hello.exe hello`
Hello, world!

二、常量和变量

rust语言和其他语言一样,也分常量和变量

  • 常亮就是一直不变的,程序中不可以更改,使用const 进行定义
  • 变量就是可变量,在Rust中分为可变变量和不可变变量
    • 不可变变量使用 let 进行定义
      -可变变量使用 let mut 进行定义

1.常量

# 正确使用
fn main() {
   
    const MAX_POINTS: u32 = 100_000;
    println!("{}",MAX_POINTS);
}
输出:100000

# 错误使用,在程序中修改常量
fn main() {
   
    const MAX_POINTS: u32 = 100_000;
    MAX_POINTS = 200_000;
    println!("{}",MAX_POINTS);
}
$cargo run hello
   Compiling hello v0.1.0 (D:\RustPro\hello)
error[E0070]: invalid left-hand side of assignment
 --> src\main.rs:3:16
  |
3 |     MAX_POINTS = 200_000;
  |     ---------- ^
  |     |
  |     cannot assign to this expression

For more information about this error, try `rustc --explain E0070`.
error: could not compile `hello` (bin "hello") due to previous error

2.变量

# 不可变变量在程序中无法修改
fn main() {
   
    let mut x:i64 = 6;
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值