go语言标准包结构 go语言的包管理工具( 二 )


func new(Type) *Type
[这位博主有非常详细的分析]
Go 语言支持并发,我们只需要通过 go 关键字来开启 goroutine 即可 。
goroutine 是轻量级线程,goroutine 的调度是由 Golang 运行时进行管理的 。
同一个程序中的所有 goroutine 共享同一个地址空间 。
语法格式如下:
通道(channel)是用来传递数据的一个数据结构 。
通道的声明
通道可用于两个 goroutine 之间通过传递一个指定类型的值来同步运行和通讯 。操作符 - 用于指定通道的方向,发送或接收 。如果未指定方向 , 则为双向通道 。
[这里有比较详细的用例]
go里面的空接口可以指代任何类型(无论是变量还是函数)
声明空接口
go里面的的强制类型转换语法为:
int(data)
如果是接口类型的强制转成其他类型的语法为:
go里面的强制转换是将值复制过去,所以在数据量的时候有比较高的运行代价
golang获取到string和直接赋值strimg不一样1、 string的定义
Golang中的string的定义在reflect包下的value.go中,定义如下:
StringHeader 是字符串的运行时表示,其中包含了两个字段 , 分别是指向数据数组的指针和数组的长度 。
// StringHeader is the runtime representation of a string.
// It cannot be used safely or portably and its representation may
// change in a later release.
// Moreover, the Data field is not sufficient to guarantee the data
// it references will not be garbage collected, so programs must keep
// a separate, correctly typed pointer to the underlying data.
type StringHeader struct {
Data uintptr
Lenint
}
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10
2、string不可变
Golang中的字符串是不可变的,不能通过索引下标的方式修改字符串中的数据:
在这里插入图片描述
运行代码 , 可以看到编译器报错 , string是不可变的
在这里插入图片描述
但是能不能进行一些骚操作来改变元素的值呢?
package main
import (
"fmt"
"reflect"
"unsafe"
)
func main() {
a := "hello,world"
b := a[6:]
bptr := (*reflect.StringHeader) (unsafe.Pointer(b))
fmt.Println(a)
fmt.Println(b)
*(*byte)(unsafe.Pointer(bptr.Data)) = '.'
fmt.Println(a)
fmt.Println(b)
}
// 运行结果
hello,world
world
unexpected fault address 0x49d7e3
fatal error: fault
[signal 0xc0000005 code=0x1 addr=0x49d7e3 pc=0x4779fa]
goroutine 1 [running]:
runtime.throw(0x49c948, 0x5)
C:/Program Files/Go/src/runtime/panic.go:1117 +0x79 fp=0xc0000dbe90 sp=0xc0000dbe60 pc=0x405fd9
runtime.sigpanic()
C:/Program Files/Go/src/runtime/signal_windows.go:245 +0x2d6 fp=0xc0000dbee8 sp=0xc0000dbe90 pc=0x4189f6
main.main()
F:/go_workspace/src/code/string_test/main.go:20 +0x13a fp=0xc0000dbf88 sp=0xc0000dbee8 pc=0x4779fa
runtime.main()
C:/Program Files/Go/src/runtime/proc.go:225 +0x256 fp=0xc0000dbfe0 sp=0xc0000dbf88 pc=0x4087f6
runtime.goexit()
C:/Program Files/Go/src/runtime/asm_amd64.s:1371 +0x1 fp=0xc0000dbfe8 sp=0xc0000dbfe0 pc=0x435da1
Process finished with the exit code 2
1
2
3
4
5
6
7
8
9
【go语言标准包结构 go语言的包管理工具】10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

推荐阅读