Golang arrays and how tiles are initialized

Source: Internet
Author: User

First, array initialization mode

    • var [length]type
var array [5]int //这种方式,只是初始化,不带初始化值,数组长度,已经定义好, 但是其实初始化的值,已经有了并且是该类型的最小值(bool false),int 0, string ' ' 其他,自行验证
    • var [n]type{value1, Value2, ..., Valuen}
var array  = [5]int{1, 2, 3, 4, 5}  // 这种方式,既初始化变量,又带了初始化值,数组长度已经定义好
    • var [...] Type{value1, value2, ..., Valuen}
var array  = [...]int{1, 2, 3, 4, 5} // 这种方式,既初始化变量,也是带了初始值,数组长度,根据初始值的个数而定,也就是五个
    • : =[n]type{value1, Value2, ..., Valuen}
array :=[5]int{1, 2, 3, 4, 5} // 这种方式,省去 var 关键词,将初始化变量和赋值,放在一起操作,这种方式简单,明了。
    • := [...] Type{value1, value2, ..., Valuen}
array := [...]int{1, 2, 3, 4, 5} // 这种方式,既初始化变量,也是带了初始值,数组长度,根据初始值的个数而定,也就是五个

Second, slice initialization mode

    • Make ([]type, length, capacity)
    • Make ([]type, length)
slice := make([]int, 5)
    • []type{}
slice := []int{}
    • []type{value1, Value2, ..., Valuen}
slice := []int{1, 2, 3, 4, 5} // 这种方式,len是根据初始化长度而定的

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.