golang中的数组与切片

golang中,当用数组去初始化一个切片时,数组的地址即为&slice[0],例子如下:

package main

import (
	"fmt"
	"math/rand"
	"net"
	"os"
	"time"
	"unsafe"
)

func main() {
	for {
		pcRecvMag()
		time.Sleep(time.Second)
	}
}

func pcRecvMag() {
	var buf [20]byte
	readFromUDP(buf[0:])
	pcHandleMsg(&buf)
}

func pcHandleMsg(p2byteArray *[20]byte) {
	fmt.Printf("byteArray pointer:%v\n",unsafe.Pointer(p2byteArray))
	fmt.Println(*p2byteArray)
}

func readFromUDP(b []byte) {
	b[0] = (byte)(rand.Intn(255))
	b[1] = (byte)(rand.Intn(255))
	fmt.Printf("len:%d,cap:%d\n",len(b),cap(b))
	fmt.Printf("slice0 pointer:%v\n",&b[0])
}
输出结果:

len:20,cap:20

slice0 pointer:0x115ad940

byteArray pointer:0x115ad940

[86 132 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

len:20,cap:20

slice0 pointer:0x1157a340

byteArray pointer:0x1157a340

[122 254 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

len:20,cap:20

slice0 pointer:0x115ad9e0

byteArray pointer:0x115ad9e0

[151 153 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]


这一点可以用slice的数据结构来解释,如下图所示:

这个是slice的数据结构,它很简单,一个指向真实array地址的指针ptr,slice的长度len和容量cap。


相关文章

什么是Go的接口? 接口可以说是一种类型,可以粗略的理解为他...
1、Golang指针 在介绍Golang指针隐式间接引用前,先简单说下...
1、概述 1.1 Protocol buffers定义 Protocol buffe...
判断文件是否存在,需要用到"os"包中的两个函数: os.Stat(...
1、编译环境 OS :Loongnix-Server Linux release 8.3 CPU指...
1、概述 Golang是一种强类型语言,虽然在代码中经常看到i:=1...