[Go] Declare Arrays and Slices in Go
There are numerous ways that you can declare and create arrays and slices in Go. This lesson will show you several and I talk about the advantages and disadvantages of one over another. After watching, you will better understand all of the possible ways you can declare/create as well as the idiomatic way.
These include:
- var
- the built-in function new
- the built-in function make
- Array and Slice literals
While it is not the main intent of this lesson, I do touch on some of the differences between slices and arrays.
package main
import (
"log"
)
func main() {
// var example - slices
var a []int
log.Printf("a type=%T, a length=%d, a capacity=%d, a=%v, nil? %t\n", a, len(a), cap(a), a, a == nil)
// new example - slices
b := new([]int)
log.Printf("b type=%T, b length=%d, b capacity=%d, b=%v, nil? %t\n", b, len(*b), cap(*b), b, b == nil)
// make examples = slices
c := make([]int, 5)
log.Printf("c type=%T, c length=%d, c capacity=%d, c=%v, nil? %t\n", c, len(c), cap(c), c, c == nil)
d := make([]int, 5, 100)
log.Printf("d type=%T, d length=%d, d capacity=%d, d=%v, nil? %t\n", d, len(d), cap(d), d, d == nil)
// var example - array
var e [3]int
//log.Printf("e type=%T, e length=%d, e capacity=%d, e=%v, nil? %t\n", e, len(e), cap(e), e, e == nil)
log.Printf("e type=%T, e length=%d, e capacity=%d, e=%v\n", e, len(e), cap(e), e)
// new example - array
f := new([3]int)
log.Printf("f type=%T, f length=%d, f capacity=%d, f=%v, nil? %t\n", f, len(f), cap(f), f, f == nil)
// slice literals
g := []int{1, 3, 6}
log.Printf("g type=%T, g length=%d, g capacity=%d, g=%v, nil? %t\n", g, len(g), cap(g), g, g == nil)
h := []int{}
log.Printf("h type=%T, h length=%d, h capacity=%d, h=%v, nil? %t\n", h, len(h), cap(h), h, h == nil)
i := []champion{
{
Name: "Evelynn",
Classes: []string{"Assassin"},
Origins: []string{"Demon"},
Cost: 3,
},
{
Name: "Vi",
Classes: []string{"Brawler"},
Origins: []string{"Hextech"},
Cost: 3,
},
}
log.Printf("i type=%T, i length=%d, i capacity=%d, i=%v, nil? %t\n", i, len(i), cap(i), i, i == nil)
// array literals
j := [3]int{1, 3, 5}
log.Printf("j type=%T, j length=%d, j capacity=%d, j=%v\n", j, len(j), cap(j), j)
k := [...]int{1, 3, 5, 7}
log.Printf("k type=%T, k length=%d, k capacity=%d, k=%v\n", k, len(k), cap(k), k)
}
Note:
If you declare a slice in Go using the var
keyword without specifying an initial size or elements, like this:
var mySlice []int
You're declaring a slice of integers that is initially nil
. This means the slice has a length and capacity of 0. Since it's nil
, you cannot directly assign values to an index like mySlice[0] = 1
because there's no underlying array allocated for the slice yet, and attempting to do so will result in a runtime panic due to an index out of range error.
To append values to this slice, you can use the append
function, which will automatically allocate an underlying array and add the new value to the slice:
mySlice = append(mySlice, 1) // Append 1 to the slice
After this operation, mySlice
will no longer be nil
; it will have a length of 1 (and a corresponding capacity that may be greater than 1, depending on how Go decides to allocate space for the slice). You can continue to use append
to add more elements:
mySlice = append(mySlice, 2, 3) // Append 2 and 3 to the slice
If you want to set values at specific indices directly without using append
, you need to ensure the slice has been initialized with a sufficient length or capacity. This can be done using the make
function, which allows you to specify an initial length (and optionally a capacity) for the slice:
mySlice = make([]int, 3) // Creates a slice of length 3 with zero values: [0, 0, 0]
mySlice[0] = 1 // Now you can directly assign values by index
mySlice[1] = 2
mySlice[2] = 3
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2023-02-18 [CSS 3] Gap
2023-02-18 [React] Scaffold a React application with pnpm and vite
2023-02-18 [Typescript] Creating a Dynamic Function with Variable Arguments
2020-02-18 [Javascript] Primitive value are immutable
2020-02-18 [ML] 2. Introduction to neural networks
2020-02-18 【逻辑思维】同一律:白马到底是不是马
2019-02-18 [NPM] Avoid Duplicate Commands by Calling one NPM Script from Another