Go language ": =" usage analysis

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

GoThe language can use " := " to complete the declaration and initialization for a new variable, as shown in the following example:

i1

Equivalent to:

var1

Note that there is no variable type in the statement, no var i int = 1 .

" := " cannot re- declare a variable that has already been declared, as shown in the following example:

package mainimport"fmt"func main() {    1    2    fmt.Println(i)}

Compilation Result:

C:/GoC:/Work/go_work/Hello.go# command-line-arguments.\Hello.go:8::=

The reason for the error is that the variable is declared repeatedly.

But when you use " := " to assign values to multiple variables, if at least one new variable is introduced, compilation is possible, as shown in the following example:

package mainimport"fmt"func main() {    1    2false    fmt.Println(i, err)}

Compile execution:

C:/GoC:/Work/go_work/Hello.go2false

Note that at this time, the "" variable is not re i -declared, only the "" "variable that was previously declared is i assigned a value.

" := " can only be used in the body of a function. One important use of this is to initialize the "," " if for and" switch "statements so that the variable becomes a" temporary variable ", that is, the scope of the variable is limited to this statement. As shown in the following example:

package mainimport"fmt"func main() {    for  35; j++ {        fmt.Println(j)    }    fmt.Println(j)}

Compilation Result:

C:/GoC:/Work/go_work/Hello.go# command-line-arguments.\Hello.go:11:undefined: j

The j declaration scope of "" is limited for to the statement, so compiling the second print statement will make an error.

Resources:
(1) Short variable declarations;
(2) Assignment operator in Go language.

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.