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

89 lines
1.4 KiB
Markdown
Raw Normal View History

2022-02-24 23:48:11 -06:00
# 字符、布尔、单元类型
### 字符
🌟
```rust, editable
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);
}
```
🌟
```rust, editable
fn main() {
let c1 = "中";
print_char(c1);
}
fn print_char(c : char) {
println!("{}", c);
}
```
2022-02-25 00:24:23 -06:00
### 布尔
2022-02-24 23:48:11 -06:00
🌟
```rust, editable
// 让 println! 工作
fn main() {
let _f: bool = false;
let t = true;
if !t {
println!("hello, world");
}
}
```
🌟
```rust, editable
fn main() {
let f = true;
let t = true && false;
assert_eq!(t, f);
}
```
2022-02-25 00:24:23 -06:00
### 单元类型
2022-02-24 23:48:11 -06:00
🌟🌟
```rust,editable
// 让代码工作,但不要修改 `implicitly_ret_unit` !
fn main() {
let _v: () = ();
let v = (2, 3);
assert_eq!(v, implicitly_ret_unit())
}
fn implicitly_ret_unit() {
println!("I will returen a ()")
}
// 不要使用下面的函数,它只用于演示!
fn explicitly_ret_unit() -> () {
println!("I will returen a ()")
}
```
🌟🌟 单元类型占用的内存大小是多少?
```rust,editable
// 让代码工作:修改 `assert!` 中的 `4`
use std::mem::size_of_val;
fn main() {
let unit: () = ();
assert!(size_of_val(&unit) == 4);
}
2022-03-01 08:06:38 -06:00
```
> 你可以在[这里](https://github.com/sunface/rust-by-practice)找到答案(在 solutions 路径下)