A common way to create and initialize arrays in the Go language summary _golang

Source: Internet
Author: User
Tags arrays

The example in this article summarizes the common ways that the go language creates and initializes arrays. Share to everyone for your reference. The specific analysis is as follows:

The syntax for the Go language is flexible, and the following shows several ways to create and initialize an array:

Copy Code code as follows:
Array initialization in various ways
Func arraySliceTest0201 () {
Create an array (declaration length)
var array1 = [5]int{1, 2, 3}
Fmt. Printf ("Array1---type:%t \ n", array1)
Rangeintprint (array1[:])

Create an array (without declaring the length)
var array2 = [...] Int{6, 7, 8}
Fmt. Printf ("Array2---type:%t \ n", array2)
Rangeintprint (array2[:])

Create an array slice
var array3 = []int{9, 10, 11, 12}
Fmt. Printf ("Array3---type:%t \ n", Array3)
Rangeintprint (ARRAY3)

Creates an array (declaring the length) and initializes only some of its elements
var array4 = [5]string{3: "Chris", 4: "Ron"}
Fmt. Printf ("Array4---type:%t \ n", Array4)
Rangeobjprint (array4[:])

Creates an array (without declaring the length) and initializes only some of its elements, the length of which is determined by the initialized element
var array5 = [...] String{3: "Tom", 2: "Alice"}
Fmt. Printf ("Array5---type:%t \ n", Array5)
Rangeobjprint (array5[:])

Creates an array slice and initializes only some of its elements, and Len of the array slice determines according to the initialized element
var array6 = []string{4: "Smith", 2: "Alice"}
Fmt. Printf ("Array6---type:%t \ n", Array6)
Rangeobjprint (ARRAY6)
}

Output an integral array of slices
Func rangeintprint (Array []int) {
For I, V: = range Array {
Fmt. Printf ("index:%d value:%d\n", I, v)
}
}

Output string Array slice
Func rangeobjprint (Array []string) {
For I, V: = range Array {
Fmt. Printf ("index:%d value:%s\n", I, v)
}
}

I hope this article will help you with your go language program.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.