📜  Rust – 常量

📅  最后修改于: 2022-05-13 01:54:48.353000             🧑  作者: Mango

Rust – 常量

常量是赋值后不能改变的值。如果我们创建了一个常量,那么就没有办法改变它的值。声明常量的关键字是const 。在 Rust 中,常量必须显式输入。以下语法用于初始化常量值:

句法 :

const VARIABLE_NAME:dataType = value;

现在让我们看看一些相同的例子。

示例 1:

Rust
fn main() {
    
   // Declare an integer constant
   const MARKS:i32 = 100;
    
   // Declare a float constant
   const PI:f32 = 3.14;  
    
   // Declare a string constant
   const NAME:&str = "GFG";
  
   // display constants
   println!("MARKS {}",MARKS);  
   println!("PI {}",PI);     
   println!("NAME {}",NAME);
}


Rust
fn main() {
    
  // Declare an integer constant
   const GFG:i32 = 100;
  
  // declaring another constant with same name
  const GFG:i32 = 200;
  
  // printing the value
  println!("{}",GFG);
}


输出:

MARKS 100
PI 3.14
NAME GFG

示例 2

fn main() {
    
  // Declare an integer constant
   const GFG:i32 = 100;
  
  // declaring another constant with same name
  const GFG:i32 = 200;
  
  // printing the value
  println!("{}",GFG);
}

这将产生一个错误