zig-learn/value/value.md
2024-06-05 09:36:08 +08:00

65 lines
6.4 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 值
## 基本数据类型
| 类型 | C 语言等效类型 | 描述 |
| -------------- | ------------------- | -------------------------------------------------------------------------------- |
| i8 | int8_t | 有符号的 8 位整数 |
| u8 | uint8_t | 无符号的 8 位整数 |
| i16 | int16_t | 有符号的 16 位整数 |
| u16 | uint16_t | 无符号的 16 位整数 |
| i32 | int32_t | 有符号的 32 位整数 |
| u32 | uint32_t | 无符号的 32 位整数 |
| i64 | int64_t | 有符号的 64 位整数 |
| u64 | uint64_t | 无符号的 64 位整数 |
| i128 | \_\_int128 | 有符号的 128 位整数 |
| u128 | unsigned \_\_int128 | 无符号的 128 位整数 |
| isize | intptr_t | 有符号指针大小的整数 |
| usize | uintptr_t, size_t | 无符号指针大小的整数 详见[#5185](https://github.com/ziglang/zig/issues/5185) |
| c_char | char | 为了与 C 语言 ABI 兼容 |
| c_short | short | 为了与 C 语言 ABI 兼容 |
| c_ushort | unsigned short | 为了与 C 语言 ABI 兼容 |
| c_int | int | 为了与 C 语言 ABI 兼容 |
| c_uint | unsigned int | 为了与 C 语言 ABI 兼容 |
| c_long | long | 为了与 C 语言 ABI 兼容 |
| c_ulong | unsigned long | 为了与 C 语言 ABI 兼容 |
| c_longlong | long long | 为了与 C 语言 ABI 兼容 |
| c_ulonglong | unsigned long long | 为了与 C 语言 ABI 兼容 |
| c_longdouble | long double | 为了与 C 语言 ABI 兼容 |
| f16 | \_Float16 | 16 位浮点数10 位尾数IEEE-754-2008 binary16 |
| f32 | float | 32 位浮点数23 位尾数IEEE-754-2008 binary32 |
| f64 | double | 64 位浮点数52 位尾数IEEE-754-2008 binary64 |
| f80 | double | 80 位浮点数64 位尾数IEEE-754-2008 80 位扩展精度 |
| f128 | \_Float128 | 128 位浮点数112 位尾数IEEE-754-2008 binary128 |
| bool | bool | 布尔值:真或假 |
| anyopaque | void | 用于类型擦除指针 |
| void | (none) | 始终为 void{}的值 |
| noreturn | (none) | the type of ,,,, and `break` `continue` `return` `unreachable` `while (true)` {} |
| type | (none) | 类型的类型 |
| anyerror | (none) | 错误代码 |
| comptime_int | (none) | 仅限于已知编译时的值。整数字面量的类型。 |
| comptime_float | (none) | 仅限于已知编译时的值。浮点字面量的类型。 |
除了上述的整数类型之外,任意位宽的整数可以通过使用标识符`i`或者`u`后跟数字来引用。例如,标识符 i7 表示有符号的 7 位整数。整数类型的最大允许位宽是 65535。
## 基本值
通常用于表示简单的数据或特殊的状态。这些基本值在编程中被广泛使用,通常用于控制逻辑、初始化变量或表示特殊的状态。下面是几种常见的基本值及其描述
| 名称 | 描述 |
| ----------------- | ----------------------------------------------------------------------------------------------- |
| `true``false` | `bool` 值用于表示逻辑真和逻辑假。 |
| `null` | 用于 [`Optioanl`](./optional.md)类型,表示该值为空。 |
| `undefined` | [`undefined`](./undefined.md)用于表示值未指定或未定义的状态,常用于初始化变量或表示缺少返回值。 |
## 字符串与 Unicode 代码字面值
与其它常见语言(`Rust`、`Java`、`C#`、`Go`)不同,在 zig 中没有专门的字符串类型zig中的字符串字面值是常量单项指针指向以空字符结尾的字节数组。
```zig
const hello: ?const[] u8 = "Hello, World!";
log.info("{s}\n", .{hello});
```
字符串字面值的类型编码既包括长度又包括以空字符结尾的事实,因此它们可以被强制转换成切片和以空字符结尾的指针,对字符串字面值进行解引用可以将其转换成数组。