Golang 的 make()、cap()、len()

本文详细解释了Golang中的make()函数用法,以及cap()和len()的区别,涵盖了数组、切片、映射和管道的容量与长度管理。
摘要由CSDN通过智能技术生成

Golang 的 make()、cap()、len()

make() 是什么

用于创建一个已初始化的切片、映射、或管道。

对比 new() : make只返回一个已初始化的对象,而new返回一个显式的指针。

固定长度限制的叫数组(Array) 不固定长度的叫切片(Slice)

键值对储存的叫映射(Map) 类似于 Python 字典

管道(Channel) 先进先出 类似于 Python Queue

package main

import "fmt"

func main() {
	array1 := [10]string{} // 有长度限制的为数组
	fmt.Println(cap(array1), len(array1))

	a := make([]string, 1, 5) // make 切片
	fmt.Println(cap(a), len(a))

	m := make(map[string]int) // make 映射 映射的容量为动态
	m["key1"] = 0
	m["key2"] = 0

	c := make(chan int, 10) // make 管道
	fmt.Println(cap(c), len(c))

	b := new([5]string)
	b[0] = "hello world"
	fmt.Println(cap(b), len(b))
}

cap() 和 len() 的区别

cap() 返回对象的容量

len() 返回对象的长度

package main

import "fmt"

func main() {
	a := make(chan int, 5) // 初始化一个管道
	a <- 1
	a <- 2
	a <- 3
	a <- 4

	fmt.Println(len(a)) // 4
	fmt.Println(cap(a)) // 5
	a <- 5
	a <- 6 // 当管道长度到达容量上限继续添加就会报错
}
fmt.Println(<-a) // 取出一个 长度-1 就可以继续添加

数组容量不够时, 继续append数组的cap会自动翻倍

package main

import "fmt"

func main() {

	c := make([]string, 0)
	c = append(c, "hello world")
	fmt.Println(len(c), cap(c)) // len 1 cap 1

	c = append(c, "hello world")
	fmt.Println(len(c), cap(c)) // len 2 cap 2

	c = append(c, "hello world")
	fmt.Println(len(c), cap(c)) // len 3 cap 4

	c = append(c, "hello world")
	fmt.Println(len(c), cap(c)) // len 4 cap 4

	c = append(c, "hello world")
	fmt.Println(len(c), cap(c)) // len 5 cap 8

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

deadmau5v

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值