Go language learning - basic grammar

Go language structure

The basic components of the Go language are as follows:

  • package declaration

  • import package

  • function

  • variable

  • Statements & Expressions

  • Notes

package main represents an independently executable program, and every Go application contains a package named main.

The main function is necessary for every executable program, and is generally the first function to be executed after startup (if there is an init() function, this function will be executed first).

Only packages with the package name main can contain the main function.

An executable program has one and only one main package.

Import other non-main packages through the import keyword.

Individual imports can be done via the import keyword:

import "fmt"
import "io"

It is also possible to import multiple at the same time:

import {
    "fmt",
    "io"
}

Use <PackageName>.<FunctionName>to call function.

Constants are defined using the const keyword.

Global variables are declared and assigned by using the var keyword outside the function body.

Use the type keyword to declare structures and interfaces.

Functions are declared with the func keyword.

When identifiers (including constants, variables, types, function names, structure fields, etc.) begin with an uppercase letter, such as: Group1, then objects using this form of identifier can be used by code in external packages (customers The client program needs to import the package first), which is called export (like public in object-oriented languages); identifiers that start with a lowercase letter are not visible outside the package, but they are visible inside the entire package and available (like protected in object-oriented languages).

Go mark

A Go program can consist of multiple tokens, which can be keywords, identifiers, constants, strings, symbols.

line separator

In a Go program, a line represents the end of a statement. Every statement doesn't need to end with a semicolon ; like other languages ​​in the C family, as this will be done automatically by the Go compiler. If you intend to write multiple statements on the same line, they must be used; artificial distinction, but we do not encourage this practice in actual development.

identifier

Identifiers are used to name program entities such as variables and types. An identifier is actually a sequence of one or more letters (A~Z and a~z), numbers (0~9), and underscore_, but the first character must be a letter or underscore and not a number.

The following are valid identifiers:

mahesh   kumar   abc   move_name   a_123
myname50   _temp   j   a23b9   retVal

The following are invalid identifiers:

  • 1ab (starts with a number)

  • case (keyword in Go language)

  • a+b (operator is not allowed)

Visibility Rules

In the Go language, case is used to determine whether the constant, variable, type, interface, structure or function can be called by an external package.

The first letter of the function name is lowercase, that is, private:

func getId() {}

The first letter of the function name is capitalized as public:

func Printf() {}

keywords

Here is a list of 25 keywords or reserved words that will be used in Go code:
write picture description here

In addition to these keywords introduced above, the Go language has 36 predefined identifiers:
write picture description here

Programs generally consist of keywords, constants, variables, operators, types, and functions.

Programs may use these delimiters: brackets (), brackets [], and curly brackets {}.

Programs may use these punctuation marks:

  • .
  • ,
  • ;
  • :

Whitespace in Go

Variable declarations in the Go language must be separated by spaces, such as:

var age int;

Appropriate use of spaces in statements makes programs easier to read.

No spaces:

fruit=apples+oranges;

Add spaces between variables and operators, the program looks more beautiful, such as:

fruit = apples + oranges; 

type of data

In the Go programming language, data types are used to declare functions and variables.

The emergence of data types is to divide data into data with different required memory sizes. When programming requires large data, it is necessary to apply for large memory, so that memory can be fully utilized.

The Go language has the following data types by category:


  1. Boolean The value of Boolean can only be the constant true or false. A simple example: var b bool = true.

  2. Number Types
    Integer int and floating-point float32, float64, Go language supports integer and floating-point numbers, and natively supports complex numbers, where the bit operation adopts complement.

  3. String type:
    A string is a sequence of characters connected by a string of fixed-length characters. Strings in Go are concatenated by individual bytes. The bytes of a Go string are encoded in UTF-8 to identify Unicode text.

  4. Derived types:
    including:
    (a) pointer type (Pointer)
    (b) array type
    (c) structured type (struct)
    (d) Channel type
    (e) function type
    (f) slice type
    (g) interface type (interface)
    (h) Map type

constant

A constant is an identifier for a simple value, an amount that will not be modified while the program is running.

The data types in constants can only be boolean, numeric (integer, float, and complex) and string.

Constants can use the len(), cap(), unsafe.Sizeof() functions to evaluate expressions. In constant expressions, the function must be a built-in function, otherwise it will not compile:

package main

import "unsafe"
const (
    a = "abc"
    b = len(a)
    c = unsafe.Sizeof(a)
)

func main(){
    println(a, b, c)
}

iota, a special constant, can be thought of as a constant that can be modified by the compiler.

At each occurrence of the const keyword, it is reset to 0, and then before the next const occurrence, the number represented by iota is automatically incremented by 1 every time the iota appears.

Using iota simplifies the definition and is useful when defining enumerations.

  • iota can only be used in constant expressions
fmt.Println(iota)  

Compile Error:undefined: iota

  • Each occurrence of const will initialize iota to 0.
const a = iota // a=0 
const ( 
  b = iota     //b=0 
  c            //c=1 
)
  • custom type

Auto-increment constants often contain a custom enumeration type, allowing you to rely on the compiler to complete auto-increment settings.

type Stereotype int

const ( 
    TypicalNoob Stereotype = iota // 0 
    TypicalHipster                // 1 
    TypicalUnixWizard             // 2 
    TypicalStartupFounder         // 3 
)
  • skippable value

Imagine you are dealing with consumer audio output. The audio may not have any output whatsoever, or it may be mono, stereo, or surround sound.

There may be some underlying logic that defines none of the outputs as 0, mono as 1, stereo as 2, and the value is given by the number of channels.

For example, to define the output value for Dolby 5.1 surround sound, on the one hand, it has 6 channels output, but on the other hand, only 5 channels are full bandwidth channels (because of the 5.1 designation - where .1 means the low frequency effects channel).

Anyway, we don't want to simply increase to 3.

We can use underscore to skip unwanted values.

type AudioOutput int

const ( 
    OutMute AudioOutput = iota // 0 
    OutMono                    // 1 
    OutStereo                  // 2 
    _ 
    _ 
    OutSurround                // 5 
)
  • bitmask expression
type Allergen int

const ( 
    IgEggs Allergen = 1 << iota // 1 << 0 which is 00000001 
    IgChocolate                         // 1 << 1 which is 00000010 
    IgNuts                              // 1 << 2 which is 00000100 
    IgStrawberries                      // 1 << 3 which is 00001000 
    IgShellfish                         // 1 << 4 which is 00010000 
)

This works because when you have only one identifier on a line in a const group, it will use the incremented iota to take the previous expression and reapply it. In the Go spec, this is called implicitly repeating the last non-empty expression list.

If you are allergic to eggs, chocolate and seafood, flip these bits to the "on" position (map the bits from left to right). Then you will get a bit value of 00010011, which corresponds to 19 in decimal.

fmt.Println(IgEggs | IgChocolate | IgShellfish)

output:
19

  • define order of magnitude
type ByteSize float64

const (
    _           = iota                   // ignore first value by assigning to blank identifier
    KB ByteSize = 1 << (10 * iota) // 1 << (10*1)
    MB                                   // 1 << (10*2)
    GB                                   // 1 << (10*3)
    TB                                   // 1 << (10*4)
    PB                                   // 1 << (10*5)
    EB                                   // 1 << (10*6)
    ZB                                   // 1 << (10*7)
    YB                                   // 1 << (10*8)
)
  • Defined on one line
const (
    Apple, Banana = iota + 1, iota + 2
    Cherimoya, Durian
    Elderberry, Fig
)

iota grows on the next line instead of taking its reference immediately.

Apple: 1
Banana: 2
Cherimoya: 2
Durian: 3
Elderberry: 3
Fig: 4

  • jumping in the middle
const ( 
    i = iota 
    j = 3.14 
    k = iota 
    l 
)

Then the printed result isi=0,j=3.14,k=2,l=3

operator

Operators are used to perform mathematical or logical operations while the program is running.

The built-in operators in the Go language are:

  • arithmetic operators
  • relational operator
  • Logical Operators
  • bitwise operators
  • assignment operator
  • other operators

    The following table lists other operators of the Go language.
    write picture description here

Conditional statements

write picture description here

loop statement

The GO language supports the following loop control statements:

  • The break statement is often used to break the current for loop or to jump out of a switch statement.

  • The continue statement skips the remaining statements of the current loop and continues with the next loop.

  • The goto statement transfers control to the marked statement.

Infinite loop

package main

import "fmt"

func main() {
    for true  {
        fmt.Printf("这是无限循环。\n");
    }
}

function

Go functions can return multiple values, for example:

package main

import "fmt"

func swap(x, y string) (string, string) {
   return y, x
}

func main() {
   a, b := swap("Mahesh", "Kumar")
   fmt.Println(a, b)
}

The execution result of the above example is:
Kumar Mahesh

Function usage
write picture description here

variable scope

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

Variables in Go can be declared in three places:

  • Variables defined inside a function are called local variables

    Variables declared in the function body are called local variables, their scope is only in the function body, and the parameters and return value variables are also local variables.

  • Variables defined outside a function are called global variables

    Variables declared outside the function are called global variables, and global variables can be used in the entire package or even external packages (after being exported).

    Global variables can be used in any function.

    The names of global variables and local variables in Go language programs can be the same, but local variables within functions will be given priority.

  • Variables in a function definition are called formal parameters

    Formal parameters are used as local variables of the function.

The default values ​​for different types of local and global variables are:

write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325768344&siteId=291194637