加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang中的数组与切片

发布时间:2020-12-16 18:14:10 所属栏目:大数据 来源:网络整理
导读:golang中,当用数组去初始化一个切片时,数组的地址即为slice[0],例子如下: package mainimport ("fmt""math/rand""net""os""time""unsafe")func main() {for {pcRecvMag()time.Sleep(time.Second)}}func pcRecvMag() {var buf [20]bytereadFromUDP(buf[0:

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:%vn",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:%dn",len(b),cap(b))
	fmt.Printf("slice0 pointer:%vn",&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。


(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读