我应该如何在Go中定义一个空片段? [英] How should I define an empty slice in Go?

查看:77
本文介绍了我应该如何在Go中定义一个空片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

或者更确切地说,我似乎可以做这三件事中的任何一件。他们之间有什么区别吗?这是最好的,为什么?


  1. var foo [] int

  2. foo:= [] int {}

  3. foo:= make ([] int,0)


解决方案

<1> is一个零分片。
$ b $ 2)和3)是非零零长度为零和容量为零的片。



游乐场示例



没有一个选项分配内存。



所有选项在Go代码中都经常使用。



因为 len cap append 使用nil slices,1)通常可以与2)和3)交换使用。

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中定义一个空片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆