Skip to content
On this page

变量6:exercises/variables/variables6.rs

题目

rust
// variables6.rs
//
// Execute `rustlings hint variables6` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

const NUMBER = 3;
fn main() {
    println!("Number {}", NUMBER);
}

题目解析

编译器错误信息如下:

txt
⚠️  Compiling of exercises/variables/variables6.rs failed! Please try again. Here's the output:
error: missing type for `const` item
 --> exercises/variables/variables6.rs:8:13
  |
8 | const NUMBER = 3;
  |             ^ help: provide a type for the constant: `: i32`

error: aborting due to previous error

错误信息提示我们const项缺少类型,并且提示我们应该为其指定一个类型: i32

rust
const NUMBER = 3; 
const NUMBER: i32 = 3; 
fn main() {
    println!("Number {}", NUMBER);
}

笔记

  • 常量 (constants) 是绑定到一个名称的不允许改变的值
  • 不允许对常量使用 mut。常量不光默认不可变,它总是不可变。
  • 声明常量时使用 const 关键字而不是 let
  • 声明常量时,必须注明值的类型
  • 常量只能被设置为常量表达式,而不可以是其他任何只能在运行时计算出的值

参考资料

Powered by VitePress