Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2.2.1节修正typo和增加说明 #1485

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion src/basic/base-type/numbers.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Rust 使用一个相对传统的语法来创建整数(`1`,`2`,...)和浮

此外,`isize` 和 `usize` 类型取决于程序运行的计算机 CPU 类型: 若 CPU 是 32 位的,则这两个类型是 32 位的,同理,若 CPU 是 64 位,那么它们则是 64 位。

整形字面量可以用下表的形式书写
整型字面量可以用下表的形式书写

| 数字字面量 | 示例 |
| ------------------ | ------------- |
Expand Down Expand Up @@ -289,6 +289,18 @@ fn main() {
```


对于移位运算,Rust 会检查它是否超出改整型的位数范围,如果超出,则会报错 overflow。比如,一个 8 位的整型,如果试图移位 8 位,就会报错,但如果移位 7 位就不会。Rust 这样做的理由也很简单,如果移位太多,那么这个移位后的数字就是全 0 或者全 1,所以移位操作不如直接写 0 或者 -1,这很可能意味着这里的代码是有问题的。需要注意的是,不论 debug 模式还是 release 模式,Rust 都会检查溢出。

```rust
fn main() {
let a: u8 = 255;
let b = a>>7; // ok
let b = a<<7; // ok
let b = a>>8; // overflow
let b = a<<8; // overflow
}
```

## 序列(Range)

Rust 提供了一个非常简洁的方式,用来生成连续的数值,例如 `1..5`,生成从 1 到 4 的连续数字,不包含 5 ;`1..=5`,生成从 1 到 5 的连续数字,包含 5,它的用途很简单,常常用于循环中:
Expand Down