Home>Article>Backend Development> Can Go language slices be multi-dimensional?
Can. Slices in the Go language support multi-dimensionality. The syntax format for declaring a multi-dimensional slice is "var sliceName [][]...[]sliceType"; if it is a two-dimensional slice, then each element of the slice is a one-dimensional slice. If the slice is a 3D slice, then each element is a 2D slice.
The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.
Go language slicing supports multi-dimensional. The syntax format for declaring a multi-dimensional slice is as follows:
var sliceName [][]...[]sliceType
Among them,sliceName
is the name of the slice ,sliceType
is the type of slice, each[ ]
represents a dimension, and the number of dimensions of a slice requires several[ ]
.
If it is a two-dimensional slice, then each element of the slice is a one-dimensional slice. If the slice is a three-dimensional slice, then each element is a two-dimensional slice.
Generally we use two-dimensional slices the most, three-dimensional slices are rarely used, and more-dimensional slices are almost never used.
Go language two-dimensional slice
Definition
var varName [][]Type
Parameters | Description |
---|---|
var | # Keywords used to define slices. |
varName | Slice name. |
Type | #The type of each element in the two-dimensional slice. |
Description
Define a two-dimensional slice varName, the type of each element of the slice is Type.
Go language three-dimensional slice
Definition
var varName [][][]Type
Explanation
Case
package main import ( "fmt" ) func main() { //创建二维切片时,可以直接初始化 var sliceHaiCoder = [][]string{{"Server", "Python"}, {"Server", "Golang"}, {"JavaScript", "Vue"}} fmt.Println("sliceHaiCoder =", sliceHaiCoder) }We created a two-dimensional slice with three rows and two columns. Each slice element is of string type, and then we use the slice initialization method to assign values to slices. Finally, we use print to print the contents of the slice.
package main import ( "fmt" ) func main() { //创建一个三维切片 var arrHaiCoder = [][][]string{{{"JavaScript", "Vue"}}, {{"Python", "Golang"}}} fmt.Println("arrHaiCoder =", arrHaiCoder) }
##[Related recommendations:
Go video tutorialThe above is the detailed content of Can Go language slices be multi-dimensional?. For more information, please follow other related articles on the PHP Chinese website!