go语言string转换 go string转int

go语言中int、int32、int64转string fmt.Sprint()的参数为interface , 可以将任意的类型转为string
函数原型:func FormatInt(i int64, base int) string
参数说明:base为进制数
base为十和十六进制数的区别的举例
Go语言int、int64、string之间的转换import "strconv"
int, err := strconv.Atoi(string)
int64, err := strconv.ParseInt(string, 10, 64)
string := strconv.Itoa(int)
string := strconv.FormatInt(int64,15)
golang获取到string和直接赋值strimg不一样1、 stringgo语言string转换的定义
Golang中的string的定义在reflect包下的value.go中,定义如下go语言string转换:
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
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
在上面的代码中,因为在go语言中不能进行指针的加减运算 , 因此取切片,让b的Data指针指向’,'所在的位置 。然后把"hello,world"中的逗号改为点,但是发现还是不行 , 程序直接崩溃了 。看来go语言中的指针得到了大大的限制 , 设计者并不想让程序员过度使用指针来写出一些不安全的代码 。

推荐阅读