我爱占星网 我爱占星网
首页
编程
java
php
前端
首页 编程 java php 前端

我应该如何在Go中定义一个空切片?

Or more precisely, it seems like I could do any of these three things. Is there any difference between them? Which is the best and why?

  1. var foo []int
  2. foo := []int{}
  3. foo := make([]int, 0)

1) is a nil slice.

2) and 3) are non-nil slices with length zero and capacity zero.

Playground example

None of the options allocate memory.

All of the options are used commonly in Go code.

Because len, cap and append work with nil slices, 1) can often be used interchangeably with 2) and 3).

近期文章

  • 如何在Go中使用与包相同名称的变量名?
  • go中是否有用于复制任意地图的内置函数?
  • Golang:托管VM应用程序的预览返回错误
  • 在go中实现io.WriterAt的缓冲区
  • 比较等于true,但是当我将其视为条件时,为什么不将其评估为true?
  • 哪些构建系统可与Go一起使用? [关闭]
  • 是否可以编写C函数来修改Go代码中定义的类型的结构?
  • Golang附加的大O
  • 如何使用godoc和go模块一起提供文档?
  • 从Go调用Python函数并获取函数返回值
  • 如何在Go中以极低的成本为禁用的日志语句执行跟踪日志记录
  • 跳过Golang中数组的第一个元素
  • 处理自定义BSON封送处理
  • 如何使用pprof工具分析基准测试?
  • 将字符串转换为float32吗?
  • interface {}进行函数类型转换
  • Golang为什么这两个字符串不相等?
  • 使用反射获取指向值的指针
  • Go中的模块化代码如何工作?
  • 函数名称前带下划线的结构标签

Copyright ©2022 我爱占星 All Rights Reserved.

浙ICP备2022030071号-1

部分图文来自网络,如有侵犯您的版权,请告诉我们删除

友情链接:代码精华