堆栈与变量逃逸
栈
- 概念
- 栈是一张拥有特殊规则的线性表数据结构
- 栈只允许往线性表的一端放入数据,之后再这一端取出数据,数据遵循后进先出(LIFO)的顺序。
- 栈和变量的关系
- 栈的分配和回收非常快,在函数内定义变量会将变量分配到栈上,函数执行结束会将执行结果保存到栈并释放变量内存。
堆
- 概念
- 堆栈都是数据结构分配的内存, 堆相较于栈来说,栈分配的内存是可预知大小的,一般用于函数内的局部变量,堆是不可预知数据大小的,适合全局变量和结构体,堆分配速度相较于栈比较慢,容易形成内存碎片。
Go语言的变量逃逸
- C/C++语言中,开发者需要自己决定如何根据算法选择选用怎样的方式分配内存, 相较与C/C++语言而言,GO语言将堆栈的分配整合到编译器中,通过分析代码特征和生命周期,来决定如何进行对或者栈的内存分配。
- 编译器决定变量应该分配到堆上还是栈上的原则有: 1.变量是否被取值、2.变量是否发生逃逸
字符串应用
字符串长度与遍历
获取字符串长度内建函数len(),返回字符串的ASCII字符长度或者字节长度,如果希望获取习惯上的字符数要使用 “unicode/utf8” 包的RuneCountInString()函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "I LOVE GO"
z := "我爱go语言"
fmt.Printf("s len长度:%d", len(s))
fmt.Printf("z len长度:%d", len(z))
fmt.Printf("z RuneCountInString长度%d\n", utf8.RuneCountInString(z))
}
// 输出:
$ go run "./字符串长度获取.go"
s len长度:9z len长度:14z RuneCountInString长度6遍历字符串
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31package main
import "fmt"
func main() {
s1 := "我爱GO语言"
for _, i := range s1 {
fmt.Printf("%c\n", i)
} // unicode for range 用value
s2 := "I LOVE GO"
for i := range s2 {
fmt.Printf("%c\n", s2[i])
} // ASCII码用下标
}
// 输出:
$ go run "./遍历字符串.go"
我
爱
G
O
语
言
I
L
O
V
E
G
O
获取一段字符串和修改字符串
- 获取字符串中的一段是利用了切片
- 修改字符串,是先将字符串转换为[]byte,然后遍历byte,根据下标修改其值
1 | package main |
多种方法连接字符串
- + 连接字符串
- fmt.Printf 格式化字符串
- 高效的连接字符串方法bytes.Buffer
1 | package main |
字符串格式化与文件读取
- 字符串格式化
示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23package main
import (
"fmt"
)
func main() {
fmt.Printf("总结%s,整理复习笔记,今天已经学习%d小时\n", "Go语言", 1)
s := fmt.Sprintf("总结%s,整理复习笔记,今天已经学习%d小时\n", "Go语言", 1)
fmt.Println(s)
fmt.Printf("%v\n", s)
fmt.Printf("%T", s)
t := 1.5
fmt.Printf("总结%s,整理复习笔记,今天已经学习%f小时\n", "Go语言", t)
}
// 输出
$ go run "./字符串格式化.go"
总结Go语言,整理复习笔记,今天已经学习1小时
总结Go语言,整理复习笔记,今天已经学习1小时
总结Go语言,整理复习笔记,今天已经学习1小时
string总结Go语言,整理复习笔记,今天已经学习1.500000小时常用的格式化样式动词及功能
动词 | 功能 |
---|---|
%s | 字符串 |
%d | 整型十进制显示 |
%f | 浮点显示 |
%p | 指针,十六进制显示 |
%T | 显示数据类型 |
%v | 按值的本身来输出 |
- 文件读取与逐行读取
1 | import ( |
strings包的常用方法
对于字符串处理, golang标准库中的strings包是一个非常强大的字符串处理包,这里列举strings包中在日常开发过程中常用的方法
1 | package main |
- 本文作者: ChuLinx
- 本文链接: http://yoursite.com/2019/12/10/Go语言复习笔记——基本语法三之堆栈与字符串应用/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!