What is an array
My summary:A variable pointing to a blockContinuous, has length , and is of the same type A piece of memory.
How to define an array
var 变量名 [元素个数]元素类型
Example:
package main func main() { //声明一个name_list数组,长度为100,里面只能放字符串 var name_list [100]string }
Note:
var 变量名 [元素个数]元素类型 等同于 var 变量名 变量类型 所以 var name1 [3]int != var name2 [4]int 因为变量类型是不一样,不可以直接进行赋值
数组初始化
package main import "fmt" func main() { //方式一,声明不赋值 //var name_list [10]int //fmt.Println(name_list) //结果:[0 0 0 0 0 0 0 0 0 0] 声明不赋值,int类型默认是0,其他类型也有默认值 // //方式二, 声明没有赋值完 //var name_list [10]int = [10]int{1, 3} //fmt.Println(name_list) //结果:[1 3 0 0 0 0 0 0 0 0],没有赋值完的,其他仍然是默认值 //方式三,声明完完全赋值 //var name_list = [3]int{1, 6, 10} //使用类型推断方式,同上 //fmt.Println(name_list) //结果:[1 6 10],每个都有值,没啥可说的 //方式四,自动推断个数 //var name_list = [...]int{1, 2, 4, 5, 19} //...表示自动推断个数,不会存在过多或者过少 //fmt.Println(name_list) //结果:[1 2 4 5 19] //方式五,指定索引方式赋值,用的很少 var name_list = [...]int{1: 66, 4: 11} //下标1赋值为66,下标4赋值11,其他默认值 fmt.Println(name_list) //结果:[0 66 0 0 11] }
数组遍历
package main import "fmt" func main() { var name_list = [...]string{"张三", "李四", "王五", "小刘"} //方式一,普通for遍历 //for i := 0; i < len(name_list); i++ { //fmt.Println(name_list[i]) //} //方式二,for range方式 for index, name := range name_list { //index是每个的下标,name是值 fmt.Println(index, name) } }
多维数组
二维数组
通常情况下,二维数组基本够用,最多三维数组,再套娃就完犊子了。
定义一个二维数组
package main import "fmt" func main() { //定义一个三行两列的一个数组 var student_list = [3][2]string{ // 列 列 {"张三", "李四"}, //行 {"王五", "小刘"}, //行 {"小七", "王八"}, //行 } fmt.Println(student_list) }
循环二维数组
同理,定义一个二维数组需要两层,循环也需要两层。
package main import "fmt" func main() { //定义一个三行两列的一个数组 var student_list = [3][2]string{ // 列 列 {"张三", "李四"}, //行 {"王五", "小刘"}, //行 {"小七", "王八"}, //行 } //方式一,普通for循环 //for i := 0; i < len(student_list); i++ { ////fmt.Println(student_list[i])//每行 ///* // [张三 李四] // [王五 小刘] // [小七 王八] //*/ //for j := 0; j < len(student_list[i]); j++ { // //每列 // fmt.Println(student_list[i][j]) //} //} //方式二,for range for _, v := range student_list { //fmt.Println(v) //每行 /* [张三 李四] [王五 小刘] [小七 王八] */ for _, b := range v { //每列 fmt.Println(b) } } }
多维数组是否可以长度推导
代码
package main import "fmt" func main() { //定义一个三行两列的一个数组 var student_list = [...][...]string{ // 列 列 {"张三", "李四"}, //行 {"王五", "小刘"}, //行 {"小七", "王八"}, //行 } fmt.Println(student_list) }
报错
似乎是不可以的,那我只用第一层试试呢。
package main import "fmt" func main() { //定义一个三行两列的一个数组 var student_list = [...][2]string{ // 列 列 {"张三", "李四"}, //行 {"王五", "小刘"}, //行 {"小七", "王八"}, //行 } fmt.Println(student_list) }
注:可以得出结论,在第一层时,是可以实现长度自动推导的。
The above is the detailed content of An article to help you understand the basics of Go language arrays. For more information, please follow other related articles on the PHP Chinese website!

Goisastrongchoiceforprojectsneedingsimplicity,performance,andconcurrency,butitmaylackinadvancedfeaturesandecosystemmaturity.1)Go'ssyntaxissimpleandeasytolearn,leadingtofewerbugsandmoremaintainablecode,thoughitlacksfeatureslikemethodoverloading.2)Itpe

Go'sinitfunctionandJava'sstaticinitializersbothservetosetupenvironmentsbeforethemainfunction,buttheydifferinexecutionandcontrol.Go'sinitissimpleandautomatic,suitableforbasicsetupsbutcanleadtocomplexityifoverused.Java'sstaticinitializersoffermorecontr

ThecommonusecasesfortheinitfunctioninGoare:1)loadingconfigurationfilesbeforethemainprogramstarts,2)initializingglobalvariables,and3)runningpre-checksorvalidationsbeforetheprogramproceeds.Theinitfunctionisautomaticallycalledbeforethemainfunction,makin

ChannelsarecrucialinGoforenablingsafeandefficientcommunicationbetweengoroutines.Theyfacilitatesynchronizationandmanagegoroutinelifecycle,essentialforconcurrentprogramming.Channelsallowsendingandreceivingvalues,actassignalsforsynchronization,andsuppor

In Go, errors can be wrapped and context can be added via errors.Wrap and errors.Unwrap methods. 1) Using the new feature of the errors package, you can add context information during error propagation. 2) Help locate the problem by wrapping errors through fmt.Errorf and %w. 3) Custom error types can create more semantic errors and enhance the expressive ability of error handling.

Gooffersrobustfeaturesforsecurecoding,butdevelopersmustimplementsecuritybestpracticeseffectively.1)UseGo'scryptopackageforsecuredatahandling.2)Manageconcurrencywithsynchronizationprimitivestopreventraceconditions.3)SanitizeexternalinputstoavoidSQLinj

Go's error interface is defined as typeerrorinterface{Error()string}, allowing any type that implements the Error() method to be considered an error. The steps for use are as follows: 1. Basically check and log errors, such as iferr!=nil{log.Printf("Anerroroccurred:%v",err)return}. 2. Create a custom error type to provide more information, such as typeMyErrorstruct{MsgstringDetailstring}. 3. Use error wrappers (since Go1.13) to add context without losing the original error message,

ToeffectivelyhandleerrorsinconcurrentGoprograms,usechannelstocommunicateerrors,implementerrorwatchers,considertimeouts,usebufferedchannels,andprovideclearerrormessages.1)Usechannelstopasserrorsfromgoroutinestothemainfunction.2)Implementanerrorwatcher


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version
Chinese version, very easy to use

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
