zoukankan      html  css  js  c++  java
  • Rust 变量

    变量声明

    let x=5;
    let (x,y) = (1,2); //x=1 y=2
    

    type annotations

    Rust 是强类型语言,我们可以在声明变量时指定类型,在编译的时候会被检查。

    x类型是 int 32位类型变量
    i 表示有符号,u表示无符号整数 ,在Rust中可以声明 8 、 16、 32、 64位的整数

    let x: i32 = 5;
    
    let y = 5; //默认是 i32
    

    Mutability

    Rust 中如果不特别标示,声明的变量都是不可变得

    let x = 5;
    x = 10; //这会编译错误
    

    错误如下:

    
    error: re-assignment of immutable variable `x`
         x = 10;
         ^~~~~~~
    

    如果需要使用可变变量,需要用到 mut 关键字

    let mut x =5; //mut x: i32
    x = 10;
    

    变量初始化

    Rust 要求在使用变量前必须对变量进行初始化

    fn main(){
        let x: i32;
        println!("hello world !!!");
    }
    

    编译会被 warn,但是依然会打印出 hello world

    
      Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world)
    src/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variable)]
       on by default
    src/main.rs:2     let x: i32;
                          ^
    

    但是如果使用时,编译器就会报错

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

    错误如下:

    
     Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world)
    src/main.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x`
    src/main.rs:4     println!("The value of x is: {}", x);
                                                        ^
    note: in expansion of format_args!
    <std macros>:2:23: 2:77 note: expansion site
    <std macros>:1:1: 3:2 note: in expansion of println!
    src/main.rs:4:5: 4:42 note: expansion site
    error: aborting due to previous error
    Could not compile `hello_world`.
    

    变量作用域

    {} 表示一个代码块,代码块内的变量 不能作用于代码块外!

    fn main() {
        let x: i32 = 17;
        {
            let y: i32 = 3;
            println!("The value of x is {} and value of y is {}", x, y);
        }
        println!("The value of x is {} and value of y is {}", x, y); // This won't work
    }
    

    Rust 有一个变态的功能,官方文档中称为 shadow,不知道如何翻译,看下代码就明白了

    let x: i32 = 8;
    {
        println!("{}", x); // Prints "8"
        let x = 12;
        println!("{}", x); // Prints "12"
    }
    println!("{}", x); // Prints "8"
    let x =  42;
    println!("{}", x); // Prints "42"
    

    同一名称的变量可以被重复声明。挺酷的一特性,但是是把双刃剑,弄好好会割伤自己
    这种重复变量声明的特性,也可以改变变量的类型。

    let mut x: i32 = 1;
    x = 7;
    let x = x; // x is now immutable and is bound to 7
    
    let y = 4;
    let y = "I can also be bound to text!"; // y is now of a different type
    

    瞬间有种在使用脚本语言的感觉。

    用放荡不羁的心态过随遇而安的生活
  • 相关阅读:
    python --异常处理
    Python -- 函数对象
    python --循环对象
    python --循环设计
    python --模块
    python --文本文件的输入输出
    xpee.vbs
    oracle 有个xe版本
    POI对Excel单元格进行颜色设置
    POI进行ExcelSheet的拷贝
  • 原文地址:https://www.cnblogs.com/re-myself/p/5532475.html
Copyright © 2011-2022 走看看