Declaration Scopes in Go

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

This post was about declaration scopes and shadowing in Go.

Package Mainimport "FMT" Func f (x intx: = 0; x < ten; PRINTLN (x)}}var x intfunc main () {var x =$ f (x)}

This program declares the four times x . All four is different variables because they exist in different scopes.

Package Mainimport "FMT" Func f () {x: = $FMT. Println ("Inside f:x =", x)}func main () {x: =. Fmt. Println ("Inside main:x =", x) F () fmt. Println ("Inside main:x =", x)}

In Go the scope of a declaration are bound to the closest pair of curly braces, { and } . In this example, we declare to be x inside main, and inside f .

What does expect this program would print?

Package Mainimport "FMT" Func Main () {x: =+ for I: = 0; i < 5; i++ {x: = ifmt. PRINTLN (x)}fmt. PRINTLN (x)}

There is several scopes in a Go program; Block scope, function scope, file scope, package scope, and universe scope. Each scope encompasses the previous. What's seeing is called shadowing.

var x =the func main () {        var x =$        fmt. PRINTLN (x)}

Most developers is comfortable with a function scoped variable shadowing a package scoped variable.

Func f () {        var x =        if x > +                x: =                . Fmt. PRINTLN (x)        }}

But a block scoped variable shadowing a function scoped variable may be surprising.

The justification for a declaration in one scope shadowing another is consistency, prohibiting just block scoped Declarati ONS from shadowing another scopes, would be inconsistent.

Related Posts:

    1. Stupid Go Declaration Tricks
    2. Associative commentary
    3. Channel axioms
    4. What's the zero value, and why is it useful?

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.