美文网首页Rust
3.1 变量和可变性

3.1 变量和可变性

作者: 剑有偏锋 | 来源:发表于2019-10-28 20:08 被阅读0次

一 创建项目

cargo new variables

二 变量可变性的实例错误代码

vim ./src/main.rs

fn main() {
    let x = 5;
    println!("The value of x is: {}", x);
    x = 6;
    println!("The value of x is: {}", x);
    
}

三 编译查看错误提示

cargo run

cargo run 
   Compiling variables v0.1.0 (/home/li/projects/variables)
error[E0384]: cannot assign twice to immutable variable `x`
 --> src/main.rs:4:5
  |
2 |     let x = 5;
  |         -
  |         |
  |         first assignment to `x`
  |         help: make this binding mutable: `mut x`
3 |     println!("The value of x is: {}", x);
4 |     x = 6;
  |     ^^^^^ cannot assign twice to immutable variable

error: aborting due to previous error

小结:默认情况,let定义的变量是不可变的,如果可变需加关键字mut

四 增加mut关键字,让变量可变

vim ./src/main.rs

fn main() {
    let mut x = 5;
    println!("The value of x is: {}", x);
    x = 6;
    println!("The value of x is: {}", x);
    
}

输出

cargo run 
   Compiling variables v0.1.0 (/home/li/projects/variables)
    Finished dev [unoptimized + debuginfo] target(s) in 4.98s
     Running `target/debug/variables`
The value of x is: 5
The value of x is: 6

五 常量

使用const关键字定义常量
const MAX_POINTS: u32 = 100_000; //在数字字面值下面插入下划线来提高数字可读性,这里等价于 100000

六 隐藏(shadowing)变量

重复使用let关键字,定义同名变量来隐藏之前的变量。
实际上是创建一个新的变量。
可改变变量的类型和值

fn main() {
    let x = 5;
    println!("The value of x is: {}", x);
    let x = "6+1";
    println!("The value of x is: {}", x);
}

如果使用mut,则会报编译错误
因为mut不允许改变变量类型

fn main() {
    let mut x = 5;
    println!("The value of x is: {}", x);
    x = "6+1";
    println!("The value of x is: {}", x);
    
}
cargo run
   Compiling variables v0.1.0 (/home/li/projects/variables)
error[E0308]: mismatched types
 --> src/main.rs:4:9
  |
4 |     x = "6+1";
  |         ^^^^^ expected integer, found reference
  |
  = note: expected type `{integer}`
             found type `&'static str`

七总结

1 使用大型数据结构时,适当地使用可变变量
2 对于较小的数据结构,总是创建新实例
3 了解let,mut,const关键字用法

相关文章

  • 3.1 变量和可变性

    一 创建项目 二 变量可变性的实例错误代码 vim ./src/main.rs 三 编译查看错误提示 cargo ...

  • Rust 编程语言-3-通用编程概念

    3. 通用的编程概念 3.1变量和可变性 变量默认都是immutable mut关键字使得变量可变,但是带来了额外...

  • 读Rust程序设计语言 - 03

    语言/Rust 变量与可变性 - Rust 程序设计语言 简体中文版 变量和可变性 在rust中变量是默认不可变的...

  • Rust语言学习小记(结构体、枚举)

    3. 结构体 3.1 结构提可变性:结构体不能单独声明某个字段的可变性,只能声明整个实例的可变性。 3.2 各种赋...

  • 3.1常量和变量

    在程序的世界中,可以让计算机按照指令做很多事情,如进行数值计算、图像显示、语音对话、视频播放、天文计算、发送邮...

  • rust学习总结-2

    声明变量 let 可变性 默认不可变mut 修饰可变 变量遮蔽(shadowing) Rust 允许声明相同的变量...

  • Python进阶6

    对象引用、垃圾回收、可变性 Python中的变量是什么 引言 Python和java中的变量本质不一样,java的...

  • 【rust学习】常见的编程概念

    一、变量和可变性 变量默认是不可改变的(immutable)。这是 Rust 提供给你的众多优势之一,让你得以充分...

  • JDK源码解析<三> java.lang.AbstractStr

    可变性 AbstractStringBuilder中变量:char value[]; int count; 都不是...

  • Swift3.0+ 学习 (一)

    变量与常量 任何Swift中的变量要么是不变的,要么是可变的。变量和常量仅仅是用来秒回持有的值的可变性,或是不可变...

网友评论

    本文标题:3.1 变量和可变性

    本文链接:https://www.haomeiwen.com/subject/jlwuectx.html