Go language learning record (1)

When learning the Hyperleger Fabric framework, in order to make it easier to read and modify the code, I taught myself the Go language, referring to the rookie tutorial. The language I am more familiar with is C++, so I often compare it with C++ when learning Go, which makes it easier to learn.

1. The basic structure of the program

The basic composition of the Go language has the following parts:

  • package declaration
  • import package
  • function
  • variable
  • Statements & Expressions
  • note

Take Hello World as an example:

package main

import "fmt"

func main() {
   /* 这是我的第一个简单的程序 */
   fmt.Println("Hello, World!")
}
  1. The first line of code  package main  defines the package name. You must indicate which package this file belongs to in the first non-comment line of the source file, such as: package main. package main represents an independently executable program, and every Go application contains a package named main .

  2. The next line  import "fmt"  tells the Go compiler that this program needs to use (a function of, or other element of) the fmt package, which implements the formatted IO (input/output) functions. import is equivalent to C++'s include, which declares the package (library) introduced by the program . The special thing is that the main package must be available, that is, the program must have a main function.

  3. The next line,  func main(),  is the function where the program starts executing. The main function must be included in every executable program. Generally speaking, it is the first function to be executed after startup (if there is an init() function, it will be executed first). Note that the main function is written as "func" + "main", there is no return type here because the main function does not need to return a value.

  4. The next line /*...*/ is a comment and will be ignored during program execution. Single-line comments are the most common form of comments, and you can use single-line comments starting with // anywhere. Multi-line comments are also called block comments, which start with /* and end with */, and cannot be nested. Multi-line comments are generally used for package documentation descriptions or code snippets commented into blocks. The annotation method is the same as C++.

  5. The next line  fmt.Println(...)  can output the string to the console, and automatically add a newline character \n at the end.
    The same result can be obtained using fmt.Print("hello, world\n").
    The two functions Print and Println also support the use of variables, such as: fmt.Println(arr). If not specified, they output the variable arr to the console in the default print format. fmt is a package that controls formatted input and output, which is similar to C++'s iostream.

  6. When the identifier (including constants, variables, types, function names, structure fields, etc.) starts with an uppercase letter, such as: Group1, then the object using this form of identifier can be used by the code of the external package (customer The end program needs to import this 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 ). This way of writing is quite special. An identifier starting with an uppercase letter is equivalent to being modified by public in C++, and an identifier starting with a lowercase letter is equivalent to being modified by protected.

The execution of a Go program is the same as other compiled languages. You can use a single command to compile and run to get the result, or you can first compile and generate an executable file, and then start the executable file to get the result.

        1. Enter the command  go run hello.go  and press Enter to execute the code.

$ go run hello.go
Hello, World!

        2. We can also use the go build command to generate binary files:

$ go build hello.go 
$ ls
hello    hello.go
$ ./hello 
Hello, World!

It should be noted that { cannot be placed on a single line, so the following code will generate an error at runtime ( this is especially important, I have always written this way in C++... ) :

package main

import "fmt"

func main()  
{  // 错误,{ 不能在单独的行上
    fmt.Println("Hello, World!")
}

2. Basic grammar of Go language

Go mark

A Go program can consist of multiple tokens, which can be keywords, identifiers, constants, strings, symbols. For example, the following GO statement consists of 6 tokens:

fmt.Println("Hello, World!")

The 6 tokens are (one per line):

1. fmt
2. .
3. Println
4. (
5. "Hello, World!"
6. )

line separator

In a Go program, a line represents the end of a statement. Each statement does not need to end with a semicolon ; like other languages ​​in the C family , because this will be done automatically by the Go compiler.

If you intend to write multiple statements on the same line, they must be used; artificially distinguished, but we do not encourage this practice in actual development.

Here are two statements:

fmt.Println("Hello, World!")
fmt.Println("菜鸟教程:runoob.com")

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 an underscore instead of a number.

The following are valid identifiers:

mahesh   kumar   abc   move_name   a_123
myname50   _temp   j   a23b9   retVal

The rules for identifiers are also the same as C++, and special attention should be paid to the "public" and "protected" effects caused by uppercase and lowercase beginnings.

string concatenation

String concatenation in Go language can be implemented with +:

package main
import "fmt"
func main() {
    fmt.Println("Google" + "Runoob")
}

The output of the above example is:

GoogleRunoob

keywords

The following is a list of 25 keywords or reserved words that will be used in Go code:

 In addition to the keywords introduced above, the Go language has 36 predefined identifiers:

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

These delimiters may be used in the program: brackets (), brackets [] and curly brackets {}.

These punctuation marks may be used in the program: ., ,, ;, :, and ….

format string

In Go language, use fmt.Sprintf to format a string and assign it to a new string:

package main

import (
    "fmt"
)

func main() {
   // %d 表示整型数字,%s 表示字符串
    var stockcode=123
    var enddate="2020-12-31"
    var url="Code=%d&endDate=%s"
    var target_url=fmt.Sprintf(url,stockcode,enddate)
    fmt.Println(target_url)
}

The output is:

Code=123&EndDate=2020-12-3

3. Go language variables

Variables come from mathematics and are abstract concepts in computer languages ​​that can store calculation results or represent values.

Variables can be accessed by variable name.

Go language variable names are composed of letters, numbers, and underscores, and the first character cannot be a number.

The general form of declaring a variable is to use the var keyword:

var identifier type
var identifier1, identifier2 type

Example:

package main
import "fmt"
func main() {
    var a string = "Runoob"
    fmt.Println(a)

    var b, c int = 1, 2
    fmt.Println(b, c)
}

The output of the above example is:

Runob
1 2

The value of an uninitialized variable is zero, where the zero value does not always refer to the value 0, and the meaning is as follows:

  • Numeric types (including complex64/128) are  0

  • Boolean type is  false

  • String is  "" (empty string)

  • The following types are  nil (nil is similar to NULL in C++) :

var a *int
var a []int
var a map[string] int
var a chan int
var a func(string) int
var a error // error 是接口

The Go language can determine the variable type by itself according to the value:

package main
import "fmt"
func main() {
    var d = true
    fmt.Println(d)
}

Output result:

true

You can also use := to declare variables and initialize them at the same time:

intVal := 1 相等于

var intVal int 
intVal =1 

var f string = "Runoob" can be shortened to f := "Runoob":

package main
import "fmt"
func main() {
    f := "Runoob" // var f string = "Runoob"

    fmt.Println(f)
}

Output result:

Runob

Note that this shorthand method can only be written in the function body, that is, it cannot be used to declare global variables.

If you declare a local variable but do not use it in the same code block, you will also get a compilation error , such as the variable a in the following example:

package main

import "fmt"

func main() {
   var a string = "abc"
   fmt.Println("hello, world")
}

Trying to compile this code will get the error  a declared but not used .

In addition, it is not enough to simply assign a value to a, this value must be used, so use

fmt.Println("hello, world", a)

will remove the error. Global variables are allowed to be declared but not used.

The rules that must be used after the local variable is declared are not available in C++, and additional attention is required when writing programs.

4. Go language constants

There is no difference between the way of writing constants and C++ when declaring them. Here is an introduction to the way of writing enumerations and the special constant iota.

enumerate

const (
    Unknown = 0
    Female = 1
    Male = 2
)

The numbers 0, 1, and 2 represent unknown gender, female, and male, respectively.

Constants can use the len(), cap(), unsafe.Sizeof() functions to evaluate expressions. In a constant expression, 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)
}

The result of running the above example is:

abc 3 16

iota

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

iota will be reset to 0 when the const keyword appears (before the first line inside const), and each new line of constant declaration in const will make iota count once (iota can be understood as the row index in the const statement block).

iota can be used as enumeration value:

const (
    a = iota
    b = iota
    c = iota
)

The first iota is equal to 0, and its value will be automatically increased by 1 whenever iota is used in a new line; so a=0, b=1, c=2 can be abbreviated as follows:

const (
    a = iota
    b
    c
)

iota is equivalent to the row index of const, adding 1 to a new row.

Look at an interesting iota example:

package main

import "fmt"
const (
    i=1<<iota
    j=3<<iota
    k
    l
)

func main() {
    fmt.Println("i=",i)
    fmt.Println("j=",j)
    fmt.Println("k=",k)
    fmt.Println("l=",l)
}

The result of running the above example is:

i= 1
j= 6
k= 12
l= 24

iota means to automatically add 1 from 0, so i=1<<0, j=3<<1 (<< meaning  left shift), that is: i=1, j=6, this is no problem, the key is k And l, from the output results, k=3<<2, l=3<<3. It can be seen that k and l are assigned along 3<<iota.

5. Operators

The operators of the Go language are exactly the same as those of C++, so they will not be recorded here~

6. Summary

The first chapter learning records include the basic structure of the Go language, basic grammar, and the introduction of variables and constants. After learning, I feel that the writing of the Go language is more convenient, such as the abbreviation for declaring local variables, the use of the special constant iota, etc. ;However, the restrictions of some rules also make it less free to write programs, such as left curly braces "{" cannot stand alone, abbreviations cannot be used for global variables, declared local variables must be used, etc., which requires me to change to write C++ Some of the habits I have retained from time to time.

Guess you like

Origin blog.csdn.net/qq_43824745/article/details/126238447