Golang-var and: Use of =

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

There are several ways to define variables in the go language.

Using var keywords is the basic way to define variables for go, and sometimes it is used to := define variables.

Defining variables

// 定义一个名称为“variableName”,类型为"type"的变量// var variableName typevar number int

Defining variables and initializing values

// 初始化“variableName”的变量为“value”值,类型是“type”// var variableName type = valuevar number int = 10

Initializing multiple variables at the same time, also called平行赋值

/*    定义三个类型都是"type"的变量,并且分别初始化为相应的值    vname1为v1,vname2为v2,vname3为v3*/// var vname1, vname2, vname3 type = v1, v2, v3var number1, number2, number3 int = 1, 2, 3

Do you think the definition above is a bit cumbersome? It doesn't matter, because the Go language designer has found that there is a way to make it easier. We can ignore the type declaration directly, then the above code becomes this:

/*    定义三个变量,它们分别初始化为相应的值    vname1为v1,vname2为v2,vname3为v3    然后Go会根据其相应值的类型来帮你初始化它们*/// var vname1, vname2, vname3 = v1, v2, v3var number1, number2, number3 = 1, 2, 3

Do you think the above is still a little cumbersome? Well, I think so, too. Let's continue to simplify:

/*    定义三个变量,它们分别初始化为相应的值    vname1为v1,vname2为v2,vname3为v3    编译器会根据初始化的值自动推导出相应的类型*/// vname1, vname2, vname3 := v1, v2, v3number1, number2, number3 := 1, 2, 3

Does it look very concise now? :=This symbol is directly replaced by var and type , this form is called 简短声明 . However, it has a limitation, which is that it can only be used inside a function, and it cannot be compiled by using outside the function, so it is generally defined by the var way 全局变量 .

换句话说,“:=”只能在声明“局部变量”的时候使用,而“var”没有这个限制。

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.