rust-by-practice/zh-CN/src/basic-types/char-bool-unit.md

99 lines
1.6 KiB
Markdown
Raw Normal View History

2022-02-24 23:48:11 -06:00
# 字符、布尔、单元类型
### 字符
1. 🌟
2022-10-10 21:43:03 -05:00
```rust,editable
2022-10-10 21:47:49 -05:00
// 修改2处 `assert_eq!` 让代码工作
2022-02-24 23:48:11 -06:00
use std::mem::size_of_val;
fn main() {
let c1 = 'a';
assert_eq!(size_of_val(&c1),1);
let c2 = '中';
assert_eq!(size_of_val(&c2),3);
println!("Success!")
2022-02-24 23:48:11 -06:00
}
```
2. 🌟
2022-10-10 21:43:03 -05:00
```rust,editable
2022-10-10 21:47:49 -05:00
// 修改一行让代码正常打印
2022-02-24 23:48:11 -06:00
fn main() {
let c1 = "中";
print_char(c1);
}
fn print_char(c : char) {
println!("{}", c);
}
```
2022-02-25 00:24:23 -06:00
### 布尔
3. 🌟
2022-10-10 21:43:03 -05:00
```rust,editable
2022-02-24 23:48:11 -06:00
2022-04-22 03:21:39 -05:00
// 使成功打印
2022-02-24 23:48:11 -06:00
fn main() {
let _f: bool = false;
let t = true;
if !t {
println!("Success!")
2022-02-24 23:48:11 -06:00
}
}
```
4. 🌟
2022-10-10 21:43:03 -05:00
```rust,editable
2022-02-24 23:48:11 -06:00
fn main() {
let f = true;
let t = true && false;
assert_eq!(t, f);
println!("Success!")
2022-02-24 23:48:11 -06:00
}
```
2022-02-25 00:24:23 -06:00
### 单元类型
5. 🌟🌟
2022-02-24 23:48:11 -06:00
```rust,editable
// 让代码工作,但不要修改 `implicitly_ret_unit` !
fn main() {
let _v: () = ();
let v = (2, 3);
2022-03-30 23:49:17 -06:00
assert_eq!(v, implicitly_ret_unit());
println!("Success!")
2022-02-24 23:48:11 -06:00
}
fn implicitly_ret_unit() {
2022-05-13 12:08:46 -05:00
println!("I will return a ()")
2022-02-24 23:48:11 -06:00
}
// 不要使用下面的函数,它只用于演示!
fn explicitly_ret_unit() -> () {
2022-05-13 12:08:46 -05:00
println!("I will return a ()")
2022-02-24 23:48:11 -06:00
}
```
6. 🌟🌟 单元类型占用的内存大小是多少?
2022-02-24 23:48:11 -06:00
```rust,editable
// 让代码工作:修改 `assert!` 中的 `4`
use std::mem::size_of_val;
fn main() {
let unit: () = ();
assert!(size_of_val(&unit) == 4);
println!("Success!")
2022-02-24 23:48:11 -06:00
}
2022-03-01 08:06:38 -06:00
```
2022-05-01 06:53:07 -05:00
> 你可以在[这里](https://github.com/sunface/rust-by-practice/blob/master/solutions/basic-types/char-bool.md)找到答案(在 solutions 路径下)