This is a go basic grammar quick entry article, learn this article, the default reader has installed Golang environment, if the environment has not been successfully installed, you can baidu.
The original address: mp.weixin.qq.com/s/zvVzP0juP…
directory
- Environmental installation
- Output statements
- Go language keyword
- type
- The data type
- Variable definitions
- Var keyword definition
- Short pattern
- Multivariable assignment
- constant
- Iota keyword
- The operator
- function
- Conditional statements and loop statements
- Conditional statements
- Looping statements
- data
- An array of
- string
- slice
- Initialize the slice
- The sample
- The map of a dictionary
- Structure struct
- interface
- grammar
- The sample
- conclusion
Environmental installation
The installation address: www.cnblogs.com/aaronthon/p/10587487.html
Output statements
No matter what language you learn, first learn the output statements of that language. As the saying goes, printing “Hello, World!” , on behalf of your entry success!!
package main
import "fmt"
func main(a) {
fmt.Println("Hello, World!")}Copy the code
Next, learn the basic grammar of go, finish the battle in 10 minutes, let’s go!!
Go language keyword
First of all, know the key words in the Go language, have an impression in the mind, let beginners have a familiar look on the line. It doesn’t matter if you can’t remember it, I will mention it again and again in the following grammar. The reason why I mention it here is so that you can take a look at it and remember it as you look at it.
type
The data type
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 memory sizes. When programming needs big 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:
Variable definitions
In mathematics, a variable is a number that has no fixed value and can be changed. But from the perspective of computer system implementation, a variable is a segment or segments of memory used to store data.
As a statically typed language, go variables always have fixed data types, which determine the length of the variable’s memory and storage format. We can only change the value of a variable, not the type.
Var keyword definition
The keyword var is used to define variables, and unlike C, the type is placed after the variable. If an initial value is explicitly provided, the variable type can be omitted and inferred by the compiler.
var X int // automatically initialize to zero
var y = false // automatically inferred as type bool
Copy the code
Multiple variables can be defined at once, of the same or different types.
var x,y int
var a,b = 100."abc"
Copy the code
Short pattern
In addition to the var keyword, you can use a shorter variable definition and initialization syntax when defining variables.
package main
import "fmt"
func main(a) {
x := 10 // Define and initialize with :=
fmt.Println(x) // Output statement 10
}
Copy the code
Some limitations of using short mode:
-
Define variables while explicitly initializing them.
-
Cannot provide a data type.
-
It can only be used inside functions, not in global variables.
Multivariable assignment
When performing multi-variable assignment operations, first calculate the value on the right side of the equal sign, and then complete the assignment operations successively.
package main
import "fmt"
func main(a){
x, y := 10.20
x, y = y+3, x+2 // First evaluate the right-hand side of the equals sign, then assign the values to x and y variables
fmt.Println(x, y) // The output statement is: 23, 12
}
Copy the code
constant
Constants represent constant, immutable values at runtime, usually literal ones. Using constants replaces the “magic number” with an easy-to-read identifier, and makes it unnecessary to change all reference code when adjusting constant values.
A constant value must be a character, string, number, or Boolean value that can be determined at compile time. Constant types can be specified or inferred by the compiler through initialization.
In the GO language, the keyword const is used to define constants.
const x, y int = 10.20
const a,b = "Michael mo coding"."Welcome, buddy."
Copy the code
Example:
package main
import "fmt"
const (
a, b string = "Michael mo coding"."Welcome, buddy."
)
func main(a) {
fmt.Println(a,b) // Maimocoding welcomes friends
}
Copy the code
Iota keyword
There is no explicit definition of enum(enumeration) in Go, but you can implement enumeration types by borrowing ioTA identifiers to implement a set of self-incremented constant values.
const (
a = iota / / 0
b / / 1
c / / 2
)
Copy the code
The values of variables A, B, and C are 0, 1, and 2, respectively, because when ioTA is used for auto-increment, the subsequent auto-increment increases in sequence. The ioTA value increases by one for each new row.
If the IOTA increment is interrupted midway, the recovery must be displayed as follows:
const (
a = iota / / 0
b / / 1
c = 100 / / 100
d // 100 (same as the constant value expression on the previous line)
e = iota // 4 (ioTA autoincrement is restored, count includes c and D)
f / / 5
)
Copy the code
The operator
Operators are used in much the same way as in other languages, which is not explained here.
package main
import "fmt"
func main(a) {
var a int = 21
var b int = 10
var c int
c = a + b
fmt.Println(c) / / 31
c = a - b
fmt.Println(c) / / 11
c = a / b
fmt.Println(c) / / 2
c = a % b
fmt.Println(c) / / 1
a++
fmt.Println(a) / / 22
a=21 // For testing purposes, a is reassigned to 21
a--
fmt.Println(a) / / 20
}
Copy the code
function
Function is to decompose the complex algorithm process into a number of smaller tasks, split, easy to maintain. Functions are designed to be relatively independent, complete a set of algorithm instructions by receiving input parameters, and output or store related results. Therefore, functions are also the basic unit of code reuse and testing.
The keyword func is used to define functions.
package main
import "fmt"
// Define Write function return two values, one is name, one is age
func Write(a) (name string, age int) {
return "Michael mo coding".1
}
// Define the Read function
func Read(name string, age int) {
fmt.Println(name, " 已经 ", age, " 岁了")}func main(a) {
Read(Write()) // Maimocoding is 1 years old
}
Copy the code
Conditional statements and loop statements
Conditional statements
Conditional statements require the developer to decide whether to execute the specified statement by specifying one or more conditions, testing whether the condition is true, and executing additional statements if the condition is false.
The following diagram shows the structure of conditional statements in a programming language:
package main
import "fmt"
func main(a) {
x := 3
if x > 5 {
fmt.Println("a")}else if x < 5 && x > 0 {
fmt.Println("b")}else {
fmt.Println("c")}}Copy the code
Looping statements
In many practical problems, there are many regular repeated operations, so some statements need to be repeated in the program.
The following is a flowchart for looping programs in most programming languages:
package main
import "fmt"
func main(a) {
for i := 0; i < 5; i++ {
if i == 4 {
continue
} else if i == 5 {
break
}
fmt.Println(i)
}
}
Copy the code
data
An array of
The Go language provides array-type data structures.
An array is a sequence of numbered, fixed-length data items of the same unique type, which can be any primitive type such as integer, string, or custom type.
package main
import "fmt"
func main(a) {
var arr1 [4]int // The element is automatically initialized to zero
fmt.Println(arr1) // [0 0 0 0]
arr2 := [4]int{1.2} // Other uninitialized elements are zero
fmt.Println(arr2) // [1 2 0 0]
arr3 := [4]int{5.3:10} // Index position can be specified
fmt.Println(arr3) // [5 0 0 10]
arr4 := [...]int{1.2.3} // The compiler determines the length of the array based on the number of initialized values
fmt.Println(arr4) / / [1 2 3]
t := len(arr4) The built-in function len(array name) represents the length of the array
fmt.Println(t) / / 3
}
Copy the code
string
The string default is not nil, but “”.
package main
import "fmt"
func main(a) {
var str string
str = "Welcome to Maimocoding."
fmt.Println(str)
}
Copy the code
slice
A slice is not itself a dynamic array or pointer. But it uses an array to store data internally, and when the array length reaches the array capacity, it will be dynamically expanded.
In plain English, slicing is similar to a List collection in Java, adding data dynamically. Unlike arrays, where the length is fixed, you need to know the data length in advance.
Initialize the slice
x := make([]int.1) // Slice is initialized with the make keyword
Copy the code
The sample
package main
import "fmt"
func main(a) {
/ / way
a := make([]int.5) // Initialize slice of length 5 with default value zero
for i := 0; i <5; i++ {
a = append(a, i)
}
a = append(a, 6)
fmt.Println(a) // [0 0 0 0 0 1 2 3 4 6]
2 / / way
var a []int
for i := 0; i < 5; i++ {
a = append(a, i)
}
fmt.Println(a) // [0 1 2 3 4]
}
Copy the code
The map of a dictionary
Map dictionaries are also frequently used data structures. Using them as language built-in types can be optimized at the runtime level for more efficient types.
As an unordered set of key-value pairs, dictionary keys must be data types that support equality operators, such as numbers, strings, Pointers, arrays, structs, and corresponding interface types.
The map dictionary function is similar to the Map collection function in Java.
Dictionaries are application types that are created using the make function or initialization statement.
package main
import "fmt"
func main(a) {
// Define the variable strMap
var strMap map[int]string
// Initialize
strMap = make(map[int]string)
// Assign a value to map
for i := 0; i < 5; i++ {
strMap[i] = "Michael mo coding"
}
// Prints the map value
for k, v := range strMap{
fmt.Println(k, ":", v)
}
// Prints the map length
fmt.Println(len(strMap))
}
Copy the code
Structure struct
Structs package sequences of named fields of different types into a compound type.
Field names must be unique and can be complemented by “_”. Members of pointer type are supported. Field attributes are base data types.
If you’ve learned Java, you can make analogies, structs can be analogies to classes in Java, fields in structs can be analogies to class member variables in Java, methods in structs can be analogies to class member methods in Java.
Struct syntax is as follows:
type user struct {
name string // Field name has a data type of string
age int // Field age has a data type of int
}
Copy the code
Example:
package main
import "fmt"
type user struct {
name string
age int
}
// Structure user Read method
func (u *user) Read(a) string {
return fmt.Sprintf("%s is % D years old", u.name, u.age)
}
func main(a) {
/ / initialization
u := &user{
name: "Michael mo coding",
age: 1,
}
fmt.Println(u.name, "Have", u.age, "Old")
// Call the Read method of the user structure
fmt.Println(u.Read()) // Maimocoding is 1 years old
}
Copy the code
interface
An interface represents an invocation contract and is a collection of method declarations.
The interface helps reduce user visibility by removing type dependence, masking internal structure and implementation details. In Go, as long as the method set of the target type contains all the methods of the interface declaration, the interface is regarded as implemented, and no display declaration is required. Of course, the target type can implement multiple interfaces.
In plain English, an interface is a collection of method declarations. If a struct class implements all methods in the interface, that class implements the specified interface.
grammar
type user interface{}Copy the code
The sample
package main
import "fmt"
// Define the interface to contain public methods
type user interface{
talking()
}
// Define a struct class
type memo struct{}// Implement the method talking in interface user
func (m *memo) talking(a) {
fmt.Println("Maimocoding welcomes you...")}func main(a) {
mm := memo{}
mm.talking()
}
Copy the code
conclusion
The article introduces the basic grammar of Go language, suitable for zero xiaobai view, so that it can quickly start the Go language project development, but after all, the article is a quick start, there are many knowledge points not talked about, readers need to learn by themselves, but also can pay attention to me, and I learn Go language together.
The article will be updated continuously. You can search “Maimo Coding” on wechat to read it for the first time. Every day to share quality articles, big factory experience, big factory face, help interview, is worth paying attention to every programmer platform.