go语言二维数组赋值 go语言数组转字符串

go语言中数组使用的注意事项和细节1、数组是多个 相同类型 的数据的组合,一个数组一旦声明/定义了,其 长度是固定的,不能动态变化。
2、var arr []int这时arr就是一个slice 切片。
3、数组中的元素可以是任何数据类型,包括值类型和引用类型,但是 不能混用。
4、数组创建后 , 如果没有赋值,有默认值如下:
数值类型数组:默认值为 0
字符串数组:默认值为 ""
bool数组:默认值为 false
5、使用数组的步骤:
(1)声明数组并开辟空间
(3)给数组各个元素赋值
(3)使用数组
6、数组的下标是从0开始的 。
7、数组下标必须在指定范围内使用,否则报panic:数组越界 , 比如var arr [5]int的有效下标为0~4.
8、Go的数组属于 值类型  , 在默认情况下是 值传递,因此会进行值拷贝 。数组间不会相互影响 。
9、如想在其他函数中去修改原来的数组,可以使用 引用传递 (指针方式) 。
10、长度是数组类型的一部分 , 在传递函数参数时,需要考虑数组的长度,看以下案例:
题1:编译错误,因为不能把[3]int类型传递给[]int类型,前者是数组,后者是切片;
题2:编译错误 , 因为不能把[3]int类型传递给[4]int类型;
题3:编译正确,因为[3]int类型传给[3]int类型合法 。
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

推荐阅读