Go Language Basic Grammar
note
Why do we write comments?
A project is made up of many. When you write, you can understand it. Half a year, one year (it’s been a long time, and I can’t understand the code when I write it myself)
Docking and projects are often completed by multiple people. (It is difficult to communicate, it is more difficult to read the code directly)
What is a comment: to describe what my current code does, or some comments
package main import "fmt" // Comments are not executed by the program // // single line comment // Notes are mainly for some businesses that I don't understand well, or complex businesses. In open source projects, comments are very complete. /* multiline comment . . . . . . Write your own understanding and current code function */ func main() { fmt.Println("Hello,World!") }
Take helloworld as an example:
// The representative is the main package. If there is a main function below, it is the entry point of the program package main // Imported a fmt package, you can use it to call the print function, output a line.... import "fmt" // main function func function main function name () no arguments func main() { // Printed a helloworld fmt.Println("Hello,World!") }
Writing comments is a very good habit. We should all write comments to our own code as required, for ourselves and for others. Many large companies also have strict requirements for annotations.
variable
variable definition
Program: We have spoken a word to the computer, and the computer needs to understand it (communication mechanism, xxx language-assembly-machine code)
The computer actually recognizes the machine code: 0 1 1 1 0 1 (high and low frequency)
Machine code: perforated paper tape
Assembly: In the early days, many low-level codes of machine hardware are assembled
Human-readable code: English, Chinese
Connect our language with the machine (C, Java, Go —> Compiler --> Execute in the computer: no need to understand, we only need to write code that we can understand)
The world we understand has a one-to-one correspondence with the computer world:
Definition: Everything needs to be defined.
Computers also need to define something.
Name of person: first name name = Night
name (variable)
name = Zhang San
name = Lisi
The computer also needs to understand the code we write in this way, and also needs a format
Variables are defined with the var keyword
Variable name Need to tell the computer what type of information (variable) is, data type: num ber, string, decimal... = "value of variable"
//Describe a person's information programmatically // string string type var name string = "Night" // int number type var age int = 27 var sex string = "male" // Java String name = "Night"
**Formula: define variable var variable name variable type **
package main import "fmt" func main() { // var variable name variable type // Define a variable, if no value is assigned to this variable, it is the default value of this data type. // string default value "" int default value 0 var name string var age int // You can define multiple variables at the same time, and you only need to use the var() keyword var ( addr string phone int ) // goland shortcut key: Copy the current line to the next line Ctrl + D fmt.Println(name) fmt.Println(age) fmt.Println(addr) fmt.Println(phone) // The use of variables can be directly manipulated after the variable is defined // Assign a value to a variable, the symbol = assignment (cannot be called equal) // Assign "Qinjiang" to the variable name. name = "Qin Jiang" // Use variables, print directly or perform some operations fmt.Println(name) // Variables can be assigned repeatedly, variables. name = "Zhang San" fmt.Println(name) // Assign values directly when defining variables. var dog string = "prosperity" fmt.Println(dog) }
Declaration of short variables (syntactic sugar, convenient for developers to develop)
package main import "fmt" func main() { // Is it okay to only define variables without using them? Theoretically yes, but actually not in Go language. // Meaningless code, error! // Question 1: Is it possible not to write the data type // Question 2: What about defining variables directly without var? // auto-deduction, a short variable declaration name := "Night" age := 18 // Syntactic sugar (lazy, simplify development!) // := is equivalent to express defining variables. If a value is assigned to this variable, its type will be automatically deduced // Definitions of var and data types are omitted. // Data type The basic data type in go language. fmt.Println(name) fmt.Println(age) // The variable name2 is defined var name2 string // In a quick declaration, if the variable to the left of := already exists, it cannot be created and cannot be redefined name3 := "zuoyi444" fmt.Println(name2) fmt.Println(name3) name3 = "zhangsan666" }
summary
1. Define variables using fixed formulas var variable name variable data type
2. Assign values to variables. When defining, assign directly, assign by variable name,
3. Syntactic sugar: = . You can use it to quickly define variables. If it is a basic data type, such as a string or a number, it will automatically deduce the type
The so-called basic grammar, all programming languages are similar.
exchange of variables
package main import "fmt" func main() { /* The first problem encountered in programming: variable exchange var a int = 100 var b int = 200 var t int t = a a = b b = t */ // In the Go language, program variable exchange also has syntactic sugar var a int = 100 var b int = 200 // fmt.Println can pass multiple parameters, separated by commas, and print directly fmt.Println("a=", a, ",b=", b) // Assigning a,b to b,a is syntactic sugar, and the underlying essence still uses temporary variables. simplify our development b, a = a, b fmt.Println("after exchange a=", a, ",b=", b) // Complex problems are simplified for us, our development is very easy, and the compiler helps us deal with them at the bottom. }
Understanding variables (memory addresses)
package main import "fmt" func main() { // What the hell is a variable? // num is actually a piece of memory space // We want to see the memory address of a variable, just add & before the variable name. // Get address character (pointer) var num int num = 1000 // Thinking: What does this num look like in a computer. num fmt.Printf("num the value of:%d,memory address:%p\n", num, &num) num = 2000 fmt.Printf("num the value of:%d,memory address:%p\n", num, &num) // compilation. understand everything var name string name = "Zhang San" // Thinking: What does this num look like in a computer. num fmt.Printf("num the value of:%s,memory address:%p\n", name, &name) name = "Li Si" fmt.Printf("num the value of:%s,memory address:%p\n", name, &name) // One of the ways to print the memory address. Print f formatted output // Memory // The first parameter output string // % Placeholder. // The number of placeholders must be the same as the number to be output later // %d number int d // %p memory address, num needs to take out the address of the variable. // %s String. // \n newline //fmt.Printf("value of num:%d",num) }
anonymous variable
package main import "fmt" // variable (with name, without name: anonymous) // Very special, anonymous variable (black hole, throw everything in, any value assigned to anonymous variable will be discarded) // _ The underscore is an anonymous variable in Go language // function A collection of pieces of code. // // func test function-name(parameters,parameters....) return something{ // A collection of codes, with or without parameters, returns the result // } // // The basic manipulation function, calling a function, returns two numbers. func test() (int, int) { // return returns the result return 100, 200 } // It will be used extensively in the Go language // Anonymous variables do not occupy memory space and do not allocate memory. func main() { // Calling this test function should return two results, 100,200 // Variable: In addition to direct definition, it can also be an assignment of a result //var a int = 100 // If you only want the first result returned by test, you need to use the anonymous variable _. a, _ := test() // a,b := 100,200 fmt.Println(a) // If you only want the second result returned by test, you need to use the anonymous variable _. _, b := test() fmt.Println(b) }
variable scope
package main import "fmt" // Global variables: take effect in the current go file... // Defined in the non-function of the go file, under package and import // The definition of global variables must use the var keyword, if you use := directly, you cannot create the variable // Global variables and local variables can have the same name, priority. who on earth var c int func main() { // Local variables: valid only within a certain range... // Declare variables inside the function body var a int = 3 var b int = 4 // If there is a global variable, then directly use the global variable to receive it. c = a + b fmt.Printf("a=%d,b=%d,c=%d\n", a, b, c) fmt.Printf("c memory address:%p\n", &c) b = 1 // But if there is a local variable with the same name as the global variable, the local variable is preferred c := a + b fmt.Printf("a=%d,b=%d,c=%d\n", a, b, c) fmt.Printf("c memory address:%p\n", &c) b = 5 // The principle of proximity c = a + b fmt.Printf("a=%d,b=%d,c=%d\n", a, b, c) fmt.Printf("c memory address:%p\n", &c) // Printf formatted output (parameter 1: the content to be printed, % is a placeholder, assign values to him one by one through subsequent parameters) fmt.Printf("a=%d,b=%d,c=%d\n", a, b, c) }
The principle of proximity
package main import "fmt" // In a Go language program, the names of global variables and local variables can be the same, but the local variables in the function body will be given priority. // string int float64 floating point number (decimal) var a float64 = 3.14 func main() { var a float64 = 2.18 fmt.Println(a) }
constant
Constant: A quantity that cannot be changed. This variable is a special variable and cannot be changed. keyword const
Two differences: variables are defined using var and constants are defined using const
What mechanism caused him to be unable to change?
The underlying convention of the Go language can actually be changed. You need to skip the constant name and directly find the memory address to modify the value.
package main import "fmt" // Constants and variables are placed at different memory addresses (stack, heap, constant pool) // The program executes normally, pushing the stack // constant func main() { // Regulations: It is recommended to do so // When we define constants, we recommend that you use capital letters to define them. Differentiate from ordinary variables // Once defined, it will not change. // Definition format const constant name [type] = value const URL string = "https://blog.csdn.net/qq_45371023" // The automatic deduction of implicit definition constants can omit some basic types, const URL2 = "www.baidu.com" // Multiple constants can be defined at the same time const URL3, URL4 string = "https://blog.csdn.net/qq_45371023", "www.baidu.com" // fmt.Println(URL) fmt.Println(URL2) fmt.Println(URL3) fmt.Println(URL4) // In our real world, there are also many variables that will not change, so the corresponding ones in the program are constants const PI = 3.14 // For fixed things, it is recommended to define them as constants. const LENGTH int = 8000 const WIDTH int = 8000 // Constants cannot be modified. //LENGTH = 13 fmt.Println(LENGTH) }
.com"
// Multiple constants can be defined at the same time
const URL3, URL4 string = "https://blog.csdn.net/qq_45371023", "www.baidu.com"
//
fmt.Println(URL)
fmt.Println(URL2)
fmt.Println(URL3)
fmt.Println(URL4)
// In our real world, there are many variables that will not change, so the corresponding ones in the program are constants
const PI = 3.14
// For fixed things, it is recommended to define them as constants.
const LENGTH int = 8000
const WIDTH int = 8000
// Constants cannot be modified.
//LENGTH = 13
fmt.Println(LENGTH)
}