# 字符串与 rune/byte 转换

URL: https://caijiao.org/go/02-composite/11-str-conversion
Source: docs/go/02-composite/11-str-conversion.md
Description: 本节介绍 Go 语言中字符串与 rune、byte 之间的转换方法，方便进行字符和字节级操作。

字符串是 UTF-8 编码的字节序列，rune 和 byte 方便不同层次的操作。

## 1. 字符串转 byte 切片

转换为字节切片，适合处理底层数据：

```go
s := "Hello"
b := []byte(s)
fmt.Println(b)  // 输出：[72 101 108 108 111]
````

## 2. 字节切片转字符串

通过转换将字节切片变回字符串：

```go
b := []byte{72, 101, 108, 108, 111}
s := string(b)
fmt.Println(s)  // 输出：Hello
```

## 3. 字符串转 rune 切片

转换为 rune 切片，适合处理 Unicode 字符：

```go
s := "Hello 中"
r := []rune(s)
fmt.Println(r)  // 输出：[72 101 108 108 111 32 20013]
```

## 4. rune 切片转字符串

```go
r := []rune{72, 101, 108, 108, 111}
s := string(r)
fmt.Println(s)  // 输出：Hello
```

---

掌握转换技巧，方便处理字符串和字符的不同需求。
