One: Go programming language Specification-block, declaration, scope

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

1. Block

The block is a pair of curly braces that enclose the declaration and statement. Block = "{" {statement ";"} "}".

In addition to the explicit source block, there is an implicit block:

      1. The full domain block contains all the go source text.
      2. Each package has a block containing all of its go source text.
      3. Each file has a block of files containing all of its go source text.
      4. Each if , for and switch statement is considered to be in its own implicit block.
      5. Each switch select clause in a statement behaves as if it were an implicit block.

Blocks can be nested and affect scope.

2. Identifiers

Identifiers are used to name program entities, such as variables and types. An identifier consists of one or more letters and numbers. The first character of an identifier must be a letter.

Given an identifier set, it is unique if one of the identifiers differs from any of the identifiers in the set. If two identifiers are spelled differently, or they appear in different packages and are not exported, they are different. Otherwise, they are the same.

Blank identifiers

A blank identifier is represented by an underscore character _, which can be used as a declaration, as with other identifiers, but the identifier cannot pass in a new binding.

Pre-declared identifiers

In a global block, the following identifiers are implicitly declared:

Type: BOOL byte complex64 complex128 error float32 float64int int8 int16 int32 int64 Rune Stringuint uint8 uint16 uint32 UINT UINTPTR constant: True false Iota 0 value: nil function: Append cap close complex copy delete imag lenmake new panic print println real recove R

exported identifiers

Identifiers can be exported to allow access from another package. The exported identifier is also the following condition:

      1. The first character of the identifier name is a Unicode uppercase letter (the Unicode category "Lu");
      2. The identifier is declared in the package block or is a field name or method name.

All other identifiers are not exported.

Key words

The following are reserved keywords and cannot be used as identifiers.

Break        default      func         interface    selectcase         defer        go           map          Structchan         Else         goto         Package      switchconst        fallthrough  if           range     typecontinue          for Import       return       var

3. Declarations and scopes

A declaration can bind a non-whitespace identifier "_" to a constant, type, variable, function, or package. In a program, each identifier must be declared.

A scope is the scope of the constant, type, variable, function, or package represented by the declared identifier in the source code.

Scope Description:

    1. The scope of a pre-declared identifier is a full-domain block.
    2. The identifier for the representation of a constant, type, variable, or function (not a method) declared at the top level (that is, outside of any function) is scoped to that package block.
    3. The package name of the imported package is scoped to the file block that contains the import declaration.
    4. Represents the identifier for a method sink, function parameter, or return value variable whose scope is the body of the function.
    5. An identifier declared as a constant or variable in a function whose scope begins at the end of a concrete constant implementation or variable implementation SHORTVARDECL a short variable declaration in the function, ending at the end of the most inner containing block.
    6. An identifier declared as a type in a function whose scope begins with the identifier of the concrete type implementation in the function, ending at the end of the most inner containing block.

Attention:

    • The same identifier cannot be declared two times in the same block, and cannot be declared at the same time in the file and package blocks.
    • An identifier declared in a block can be re-declared in its inner block. When an internally declared identifier is in scope, it means that its entity is declared in that internal declaration.
    • The BUN clause (package XXX) is not a statement; The pack name does not appear in any scope. The purpose is to identify whether the file belongs to the same package and specify the default package name for the import declaration.

Label Scope:

tags are declared (identifier: statements) through a label statement and are used for break, continue, and goto statements. For example:

L:      for i < n {        switch  i {        case5:              break L        }    }

It is illegal to define a label that will not be used. As opposed to other identifiers, labels are not scoped and do not conflict with non-tag identifiers. The scope of a label is the body of the function that it declares in addition to any nested function body.

4. Various declarations

Constant declaration

ConstPi float64 =3.14159265358979323846ConstZero =0.0       //Untyped floating-point constantsConst(Size Int64=1024x768EOF= -1    //Untyped Integer Constants)ConstA, b, C =3,4,"Foo"  //A = 3, B = 4, c = "foo", untyped integers and string constantsConstU, v float32 =0,3    //u = 0.0, v = 3.0

Iota

Iota can be thought of as a constant that can be modified by the compiler, is reset to 0 when each const keyword appears, and then each time a iota occurs before the next const appears, the number represented automatically increases by 1

Const (  //  Iota reset to 0    C0 = Iota  //  C0 = = 0    c1 = Iota  // C1 = = 1    C2 = Iota  //  C2 = = 2)const  (    = Iota    Monday    Tuesday    Wednesday    Thursday    Friday    partyday    numberofdays  //  The constant is not exported )

In the expression list, the value of each iota is the same because it is incremented only after each constant implementation.

Const (    111  //  bit0 = = 1, Mask0 = = 0    bit1, Mask1                           // Bit1 = = 2, Mask1 = = 1    _, _                                  //  Skips iota = = 2    bit3, mask3                           //  bit3 = = 8, Mask3 = 7)

Type declaration

A claim type does not inherit any method bound to an existing type, but the set of methods for an interface type or compound type element remains the same:

//The mutex is a data type with two methods, lock and unlock.Type Mutexstruct{/*Mutex Fields*/}func (M*mutex) Lock () {/*Lock Implementation*/}func (M*mutex) Unlock () {/*Unlock Implementation*/ }//Newmutex and mutexes have the same composition, but their method set is empty.type Newmutex Mutex//The set of methods for the underlying type of Ptrmutex remains unchanged.//However, the Ptrmutex method set is empty.Type Ptrmutex *Mutex//*printablemutex Method Set contains methods//lock and unlock are bound to their anonymous field mutexes.Type Printablemutexstruct{Mutex}//Myblock is an interface type that has the same set of methods as the block.Type Myblock Block

Type declarations can be used to define different Boolean, numeric, or string types and attach methods to them:

int Const (    =-(5 + iota)    CST    MST    string  {    return FMT. Sprintf ("gmt+%dh", TZ)}

Variable declaration

A variable declaration binds an identifier to a created variable and assigns it a type and an optional initial value.
Given an expression list, the variable is initialized by assigning the expression to the variable (§ Assignment) in order, all expressions must be exhausted, and all variables are initialized according to them.
Otherwise, each variable is initialized to its 0 value. If the type already exists, each variable is given the type.
Otherwise, the type is assigned a value based on the expression list.
If the type does not exist and its corresponding expression evaluates to an untyped constant, the type of the declared variable is described by its assigned value.

Implementation restrictions: If you declare a variable that is not used in the body of the function, the compiler may decide that it is illegal

varIintvarU, V, W float64varK =0varX, y float32 =-1, -2var(iintU, V, s=2.0,3.0,"Bar")varRe, im = Complexsqrt (-1)var_, found = Entries[name]//mapping check; only related to "found"

Short variable Declaration

A short variable declaration can only appear inside a function. In some cases, such as initializing if, for, or switch statements, they can be used to declare local temporary variables

0 Ten F: int return 7 }ch:int) R, w:= os. Pipe (FD)  //  OS. Pipe () returns two values _, Y, _: = Coord (P)  //  coord () returns three values, only related to values that are the same as Y

Unlike regular variable declarations, when there is at least one non-whitespace variable, a short variable declaration can be declared with the same type as the previously declared variable in the same block. Therefore, a re-declaration can only appear in a variable short declaration. A re-declaration cannot generate a new variable; it can only give a new value to the original variable.

0 ) Field2, offset:= NextField (str, offset)  //  re-declare offset  in the same block using VAR duplicate declaration is illegal 1  2                              //  illegal: repeatedly declares a, or if a is declared elsewhere, but there are no new variables

function declaration

function declarations omit function bodies. Such identifiers provide signatures for functions implemented outside the go, such as assembly routines.

int int int {    if x < y {        return  x    }    return  y} Func Flushicache (begin, End uintptr)  //  External implementation

Method declaration

The method is a function with a receiver. The method declaration binds the identifier, the method name, to the method. It also associates the underlying type of the recipient to the method.
The recipient type must be either form T or *t, where T is the type name.
The type represented by T is called the underlying type of the receiver; it cannot be a pointer or interface type and must be declared as a method in the same package.

If the value of the receiver is not referenced in the method body, its identifier can be omitted from the declaration. The same applies to the formal parameters of a general function or method.

Func (P * Point) Length () float64 {    return math. SQRT (p.x * p.x + p.y ** point) scale (factor float64) {    *= factor    *= factor}func (Po int) scale (factor float64) {    

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.