1. Go’s keyword list and classification
Introduction
Keywords are a set of special words predefined in programming languages. Each keyword has a clear function and purpose. In the Go programming language, keywords play the role of building a program logical framework and are the basis of program semantics and structure. This article aims to deeply explore the positioning and application of keywords in Go to understand its importance in programming. The Go language has 25 predefined keywords that are used for various specific purposes, from declaring variables and functions, to flow control and concurrent programming.
break, default, func, interface, select, case, defer, go, map, struct, chan, else, goto, package, switch, const, fallthrough, if, range, type, continue, for, import, return, var
Positioning of keywords in Go
The cornerstone of language
Keywords are the basic building blocks in any programming language, and Go is no exception. They are tools for describing program logic, defining data structures, and handling errors, among other tasks.
Simple and efficient
The Go language is widely popular for its simplicity and efficiency, largely due to its limited but highly optimized set of keywords. Go has only 25 keywords, which is a relatively small number compared to other programming languages, but each keyword has a clear and important purpose.
Scalability and Flexibility
While the keywords themselves are fixed, Go provides a range of compound statements and operators for a high degree of scalability and flexibility. For example, you can create complex logical structures using the if-else, for, and switch keywords.
Keyword classification
Declaration of various code elements
Keywords | Description |
---|---|
const | Used to declare one or more constants |
func | Used to define new functions |
import | is used to import external packages |
package | is used to declare the package name, usually located at the end of each Go source file The first line |
type | is used to declare custom types, such as structures, interfaces, aliases, etc. |
var | is used to declare one or more variables |
Literal representation of combined type
Keywords | Description |
---|---|
chan | Used to declare a new channel (channel) |
interface | Used to define a new interface |
map | is used to declare a new map (key-value storage) |
struct | is used to define A new structure |
Basic flow control syntax
Keywords | Description |
---|---|
break | Used to interrupt the current loop or one of the switch statements |
case | switch statements Branch |
continue | Skip the remaining statements of the current loop iteration and enter the next iteration |
default | switch The default branch in the switch statement |
else | if The negative branch of a statement |
fallthrough | is used in the switch statement to allow the control flow to continue executing the next case |
for | for loops |
goto | Jump to label (not recommended) |
if | Conditional statement |
range | Used for for loops to traverse arrays, slices, maps or channels |
return | For returning values from functions |
select | For multi-channel selection |
switch | For multi-branch selection statements |
Coroutines and delayed function calls
Keywords | Description |
---|---|
defer | Used to delay the execution of functions, usually used to clean up resources |
go | Used to start a new goroutine to achieve concurrency |
Second, Go keyword full code example
Keyword full code example
Keywords | Code examples | Code function |
---|---|---|
const | const PI = 3.14159 |
Define constant PI |
func | func add(x, y int) int { return x + y } |
The definition is named add Function |
import | import "fmt" |
Import fmt package |
package | package main |
Define the package name main |
type | type Point struct {x, y int} |
Define a Structure named Point |
var | var name string = "John" |
Define a variable named name |
chan | ch := make( chan int) |
Create a new integer type channel |
interface | type Writer interface { Write([]byte) error } |
Define an interface named Writer |
map | m := map[string]int{"one": 1} |
Create a map where the key is a string and the value is an integer |
struct | type Circle struct { Radius float64 } |
Define a structure named Circle ‘s structure |
break | if x > 0 { break } |
if x > 0 , then break out of the loop |
case | case "apple": fmt.Println("It's an apple") |
In the switch statement, define a case |
continue | if x < 0 { continue } |
If x < 0 , skip the current loop iteration |
default | default: fmt.Println("It's default") |
In switch statement, define a default case |
else | if x > 0 { /*. ..*/ } else { /*...*/ } |
The negative branch of if statement |
fallthrough | case 1: fallthrough |
In the switch statement, force the next case |
for | for i := 0; i < 10; i + + { /*...*/ } |
Loop 10 times |
goto | goto myLabel |
Jump to myLabel label (not recommended) |
if | if x > 0 { /*. ..*/ } |
When the condition is x > 0 , perform an operation |
range | for k, v := range m { /*...*/ } |
Traverse mapping m |
return | return x + y |
Return x + y |
select | select { case <-ch: /*...*/} |
Multiple channel selection |
switch | switch x { case 1: /*...*/ } |
Multiple branch selection |
defer | defer fmt.Println("bye") |
Delay execution of fmt.Println("bye") until the function exits |
go | go doSomething() |
Execute the doSomething() function in the new goroutine |
Three, Go identifier definitions
Identifiers are names used in programming languages to identify various programming elements (such as variables, functions, types, etc.). In the Go language, identifiers have a specific set of rules and conventions. These rules and features are explained in detail below.
Basic definition
An identifier is a word that begins with a Unicode letter or an underscore (_
) and consists entirely of Unicode letters and Unicode digits.
- Unicode letters: These are the characters defined in the Lu, Ll, Lt, Lm and Lo categories of the Unicode standard 8.0.
- Unicode digits: These are characters defined in the Nd numeric character class defined in Unicode Standard 8.0.
Special Regulations
Keywords and Identifiers
Go keywords cannot be used as identifiers. This is an important restriction to avoid naming conflicts and syntax confusion.
empty identifier
The identifier _
is a special character called the null identifier. It is used to ignore a certain return value of a function or to force a variable to be declared but not used.
Scope and Visibility
- Exported identifier: An identifier starting with a Unicode capital letter is called an exported identifier, which can also be understood as public.
- Non-exported identifiers: Other identifiers (that is, those starting with non-Unicode capital letters) are called non-exported identifiers, which can also be understood as private.
Note: As of now (Go 1.20), Eastern characters are considered non-exported characters.
Example of legal identifier
Export Identifier
Player_9
DoSomething
VERSION
?o
Π
non-exported identifier
_
_status
memStat
book
π
A type
エラー
Illegal identifier
- Begins with Unicode numbers:
123
,3apples
- Contains unqualified Unicode characters:
a.b
,*ptr
,$name
,[email protected]
- Use keywords:
type
,range
Four. Examples of Go identifiers
In the Go language, identifiers are used to name various types of programming elements, such as variables, constants, functions, etc. This article will provide code examples and related explanations for different types of identifiers in the form of tables.
Table: Go identifier types, examples and explanations
Identifier types | Identifier examples | Explanation |
---|---|---|
Variable | myVariable |
is used to store data values. |
Constant | MAX_COUNT |
is used to store data values that will not change. |
Function | CalculateSum |
Contains a block of code that performs a specific task. |
Structure | Person |
is used to define a compound containing multiple fields (variables) type of data. |
Interface | Writer |
defines a set of methods, and any type that implements these methods is considered to implement this interface. |
Slice | mySlice |
Dynamic array that can change size at runtime. |
Map | colorMap |
A collection of key-value pairs. |
Channel | msgChannel |
is used to send and receive data between Goroutines. |
Package | fmt |
is used to organize and reuse code, usually including functions and variables , constants, etc. |
Alias | type MyInt int |
is used to create a new name for an existing type. |
Enumeration | enum Status |
A set of named integer constants. |
Goroutine | go doSomething() |
Function executed concurrently. |
Tag | LOOP: |
is used for control flow statements, such as break and continue . |
The empty identifier | _ |
is used to ignore unwanted values. |
Export identifiers | PublicVar |
Identifiers that are visible and available in other packages. |
Non-exported identifier | privateVar |
Visible and available only within the package in which it is defined identifier. |
Five. Go keywords and identifier codes in practice
In this section, we will explore the practical application of all keywords and identifiers in Go through a comprehensive practical code example. We will create a simple calculator program that will perform four operations: addition, subtraction, multiplication, and division.
Comprehensive case: simple calculator
package main // package keyword is used to define the package name import "fmt" // The import keyword is used to introduce external packages //Global variable declaration var result int // The var keyword is used to declare variables const maxInput = 100 // const keyword is used to declare constants // Custom type declaration type Calculator func(int, int) int // The type keyword is used to declare a custom type // main function func main() { // func keyword is used to declare functions var operator string // local variable declaration var num1, num2 int for { // for keyword is used for looping fmt.Println("Please enter the operator ( + , -, *, /, exit):") fmt.Scanln(&operator) if operator == "exit" { // if keyword is used for conditional judgment fmt.Println("Program exited.") break // break keyword is used to break out of the loop } fmt.Println("Please enter two integers:") fmt.Scanln( & amp;num1, & amp;num2) switch operator { // switch keyword is used for multi-condition judgment case " + ": result = calculate(add, num1, num2) case "-": result = calculate(subtract, num1, num2) case "*": result = calculate(multiply, num1, num2) case "/": if num2 == 0 { // else keyword is used for conditional judgment fmt.Println("The divisor cannot be 0") continue // The continue keyword is used to skip this loop } result = calculate(divide, num1, num2) default: // The default keyword is used for multi-condition default options fmt.Println("Invalid operator") continue } fmt.Printf("The result is: %d\ ", result) } } // Function declaration and definition func calculate(calc Calculator, num1, num2 int) int { return calc(num1, num2) } // addition func add(a, b int) int { return a + b } // subtraction func subtract(a, b int) int { return a-b } //Multiplication func multiply(a, b int) int { return a * b } // division func divide(a, b int) int { return a/b }
Keywords and identifiers parsing
package
: Defines the package to which the current code belongs, here ismain
.import
: Used to introduce external libraries. Here we introduce thefmt
library.var
: global and local variable declarations.const
: Used to define constants. A constant namedmaxInput
is defined here.type
: Used to declare a custom type. ACalculator
function type is defined here.func
: used to declare functions. Multiple functions are declared here.for
: used for loops, here is an infinite loop.if
,else
: used for conditional judgment.switch
,case
,default
: used for multi-condition judgment.break
: used to break out of loops.continue
: used to skip the current loop iteration.