Go language keyword analysis: In-depth understanding of keywords in Go language

Abstract: This article was originally published on CSDN by the technical team of Grape City. Please indicate the source of the reprint: Grape City official website , Grape City provides developers with professional development tools, solutions and services to empower developers.

foreword

In order to introduce the Go language and the comparison with the C# language in more depth, this article will elaborate in detail from multiple dimensions. First, it will introduce the similarities and differences between Go and C# in terms of the keywords of the Go language, and discuss the optimization and shortcomings of the two languages ​​in terms of keywords. Secondly, this article will demonstrate the advantages of the Go language in terms of keywords through code examples, performance tests, etc., so as to present the power of the Go language to readers. In addition, in order to better help readers understand the Go language, this article will also introduce some excellent Go language tools and community resources for readers to learn and explore further. I believe that through the comprehensive introduction of these contents, readers will have a more comprehensive and in-depth understanding of the Go language.

Article directory:

1. Past and present life of Go

​1.1  The birth process of Go language

​1.2  Step by step forming

​1.3  officially released

​1.4  Go Installation Guide

2. Keyword comparison between Go and C#

​2.1  Keywords in both Go and C#

​2.1.1. Var  

​  2.1.2. Switch-case-default

​  2.1.3.If-else

​  2.1.4. For

​  2.1.5. Struct

​​​​2.2Keywords that are not the same between Go 

​2.2.1   . Package and namespace

2.2.2   . Import and using

2.2.3   . Type and class

​2.2.4   . Defer and finally

​2.3Keywords that Go 

​​  2.3.1. Fallthrough

​​  2.3.2.Func

3. Extended link

1. Past and present life of Go

1.1 The birth process of Go language

It is said that as early as one day in September 2007, Google engineer Rob Pike started the construction of a C++ project as usual. According to his previous experience, this construction should last about 1 hour. At this time, he and two other Google colleagues, Ken Thompson and Robert Griesemer, began to complain and expressed their idea of ​​​​a new language. At that time, Google mainly used C++ to build various systems internally, but the complexity of C++ and the lack of native support for concurrency made the three big bosses very distressed.

The small talk on the first day was fruitful, and they quickly conceived a new language that could bring joy to programmers, match future hardware development trends, and satisfy Google's internal large-scale network services. And on the second day, they met again and began to seriously conceive the new language. After the meeting the next day, Robert Griesemer sent the following email:

It can be seen from the email that their expectations for this new language are: **On the basis of the C language, modify some errors, delete some criticized features, and add some missing functions. **Such as repairing the Switch statement, adding an import statement, adding garbage collection, supporting interfaces, etc. And this email became the first draft of Go's design.

A few days after this, Rob Pike came up with the name Go for the new language on a drive home. In his mind, the word "Go" is short, easy to type and can easily be combined with other letters after it, such as Go's tool chain: goc compiler, goa assembler, gol linker, etc., and this word also fits Their original intention for the language design: simple.

1.2 Step by step forming

After unifying the design ideas of Go, the Go language officially started the design iteration and implementation of the language. In 2008, Ken Thompson, the father of the C language, implemented the first version of the Go compiler. This version of the Go compiler is still developed in the C language. Its main working principle is to compile Go into C, and then Compile C into binaries. By mid-2008, the first version of Go's design was largely complete. At this time, Ian Lance Taylor, who also worked at Google, implemented a gcc front-end for the Go language, which is also the second compiler of the Go language. This achievement of Ian Taylor is not only an encouragement, but also a proof of the feasibility of Go, a new language. With a second implementation of the language, it is also important to establish Go's language specification and standard library. Subsequently, Ian Taylor officially joined the Go language development team as the fourth member of the team, and later became one of the core figures in the design and implementation of the Go language. Russ Cox is the fifth member of the Go core development team, also joining in 2008. After joining the team, Ross Cox cleverly designed the HandlerFunc type of the http package by taking advantage of the feature that the function type is a "first-class citizen", and it can also have its own methods. In this way, we can make an ordinary function a type that satisfies the http.Handler interface through explicit transformation. Not only that, Ross Cox also proposed some more general ideas based on the design at that time, such as the io.Reader and io.Writer interfaces, which established the I/O structure model of the Go language. Later, Ross Cox became the head of the Go core technical team, promoting the continuous evolution of the Go language. At this point, the initial core team of the Go language is formed, and the Go language has embarked on a path of stable evolution.

1.3 officially released

On October 30, 2009, Rob Parker gave a speech on the Go language at Google Techtalk, which was the first time that the Go language was made public. Ten days later, on November 10, 2009, Google officially announced that the Go language project was open source, and this day was officially designated by Go as the birth day of the Go language.

(Go language mascot Gopher)

1.4. Go installation guide

1. Go language installation package download

Go official website: https://golang.google.cn/

Just select the corresponding installation version (it is recommended to select the .msi file).

2. Check whether the installation is successful + whether the environment is configured successfully

Open the command line: win + R to open the run box, enter the cmd command, and open the command line window.

Enter go version on the command line to view the installed version. If the following content is displayed, the installation is successful.


2. Keyword comparison between Go and C#

Go has 25 keywords, while C# has 119 keywords (including 77 base keywords and 42 context keywords). In terms of quantity alone, the number of C# is 5 times that of Go, which is one of the reasons why Go is simpler than C#.

25 keywords in Go:

break default func interface select
case defer go map struct
chan else goto package switch
const fallthrough if range type
continue for import return was

(Go keyword)

2.1 Keywords in both Go and C#

  • break
  • case
  • const
  • continue
  • default
  • else
  • for
  • goto
  • if
  • interface
  • return
  • struct
  • switch
  • was

The above 14 keywords are shared by Go and C#, and most of them are used in exactly the same way. Here we will focus on the keywords with special syntax in Go.

2.1.1. Var

Var is used to define variables in Go, but the syntax is different from C#. There is only one way to define variables in C#, but there are two ways in Go, they are:

  • normal way
var i int = 1

This method is Go’s original variable definition method, and generally package-level variables are defined in this way, and if you define those types that the compiler can automatically infer, such as the above example, the subsequent types can be omitted.

  • Syntactic sugar (yes, there is syntactic sugar in Go too...)
i, j := 1, "hello"

The above code can be abbreviated as syntactic sugar. In fact, 90% of variables in Go code are defined in this way, because almost all functions have multiple return values, and this way of defining can save a lot of trouble.

2.1.2.Switch-case-default

Switch-case is a method that can be used in conjunction, but the two keywords case and default can be used in conjunction with the select statement in addition to the switch in Go.

At the same time, Go fixes a drawback of the switch statement by default, that is, there is no need to write break in the switch clause.

switch n := "a"; n {
    
    

case n == "a":

fmt.Println("a")

case n == "b":

fmt.Println("b")

case n == "c":

fmt.Println("c")

}

The fmt of the above code is the standard output package in Go, and the Println function is equivalent to the Console.WriteLine method in C#. At the same time, the final result of this code will only output a, while in C#, the same code will output all abc, which is one of the reasons why Go is simpler than C#.

In addition, a new way of writing appears behind the switch statement: n := "a"; n, this way of writing can be used in control statements (if, else if, switch-case, for) in Go , before the semicolon is the definition of the variable, after the semicolon is the definition of the judgment condition. This syntactic advantage is similar to the first two clauses of a normal for loop in C#.

Finally, it can be found that there are no parentheses after the switch, because in Go, parentheses are not required after the clauses of the control block, and if they are written, they will also be automatically formatted by gofmt.

2.1.3. If-else

The if-else in Go is almost the same as C#. The biggest difference between them is the special syntax in Go. You can directly assign values ​​to variables in the if-else control block and use these values ​​​​in the control block.

func isEven(n int) bool {
    
    

return n % 2 == 0

}

func main() {
    
    

if n := rand.Intn(1000); isEven(n) {
    
    

fmt.Printf("%d是偶数\\n", n)

} else {
    
    

fmt.Printf("%d是奇数\\n", n)

}

}

2.1.4. For

The loop control statement in Go has one and only one for keyword. While and foreach in C# are all achieved through various variants of for in Go.

  • while statement
for true {
    
    

// ...

}
  • for statement
for i := 0; i < n; i++ {
    
    

// ...

}

The only difference between a normal for loop in Go and C# is that i++ has changed from an expression to a statement. In other words, there is no syntax like i = i++ in Go, and there is no syntax like ++i, only i++.

  • foreach statement
array := [5]int{
    
    1, 2, 3, 4, 5}

for index, value := range array {
    
    

// ...

}

The writing method of the foreach statement is very different from that in C#. The above example is that foreach traverses an array of int type, and a range keyword is used in it. This keyword will split the array into two iteration sub-objects index and value, for range can traverse arrays, slices, strings, maps, and channels (channels). This syntax is also similar to JavaScript's loop syntax. For example, the following code is to traverse the values ​​in the array and output:

for key, value := range []int{
    
    1, 2, 3, 4} {
    
    

fmt.Printf("key:%d value:%d\\n", key, value)

}

The code output is as follows:

key:0 value:1

key:1 value:2

key:2 value:3

key:3 value:4

2.1.5 Struct

The struct keyword in Go has the same function as in C#, that is, to define a structure. Because there is no concept of class in Go, struct is equivalent to the definition of class in C#. Similarly, struct is a value type structure in Go , so when using it, you must pay attention to the copy problem caused by value transfer. ( It should be noted that struct in Go can only define fields, not functions.)

// struct的定义是配合type关键字一起使用的

type People struct {
    
    

name string // 定义的字段和Go语言其他的风格相同,名字在前,类型在后

age int

}

2.2Keywords that are different between Go and C# but used in similar ways

  • package
  • import
  • type
  • defer

2.2.1.Package and namespace

The package in Go is basically the same as the namespace in C#. It is a package that defines an organization, and its main function is to isolate code modules. But the difference between Go and C# is that C# is very flexible, even codes that are not in the same folder can be defined as the same namespace. However, the files in the package in Go need to be in the same folder to be compiled correctly, and only one package name can appear in a folder. In addition, similar to the Main method in C#, the execution entry of a runnable program in Go is also a main function, but the main function must be defined under package main.

// Go中,同一个文件夹只能同时存在一个包名

// 包名可以和文件夹名不同,但是必须有且只有一个

package main

// main函数只能在main包下才能正确作为启动函数运行

func main() {
    
    

//do something

}

// 同文件夹下的另一个文件,比如hello.go

package hello //编译器报错

2.2.2.Import and using

Both Import and using are used to import code from other modules. But Go has one more mandatory requirement than C#: If you do not use import in the code module or define but not used variables, an error will be reported directly when compiling. In addition to making the code look more concise, the main reason for this is that the import statement has another important function, which is to call the init() function in the package. For example the following code:

// hello文件夹下的demo文件夹内的 demo.go

package demo

var me string

func init() {
    
    

me = "jeffery"

}

func SayHello() {
    
    

fmt.Printf("hello, %s", me)

}

// hello文件夹下的hello.go

package main

import "hello/demo"

func main() {
    
    

demo.SayHello() // 输出:hello, jeffery

}

The above program defines a demo file. When the demo file is loaded into other packages by the import keyword for the first time, its init() function will be called automatically. At this time, the variable me will be assigned as jeffery, and then SayHello() will be called. function, it returns "hello, jeffery". It is precisely because of the existence of the init function that the unused import needs to be deleted, because if it is not deleted, it is likely to automatically call the init function in the unused package.

2.2.3. Type and class

  • conventional usage

It is not reasonable to compare type and class. Because the class keyword in C# is to define a type and the specific implementation of this type, for example, the following code in C# means to define a class named People, and define an attribute Age in this class.

interface IAnimal {
    
    

public void Move();

}

class People {
    
    

public int Age {
    
     get;set; }

}

However, the type keyword in Go is only used to define the type name. If you want to define its implementation, you must add specific implementation keywords later. For example, the above code definition becomes as follows in Go:

type IAnimal interface {
    
    

Move()

}

type People struct {
    
    

Age int

}

The above is just the most common usage of type, in addition to type there are two other usages:

  • define a new type in terms of a base type
type Human People

Such a statement is equivalent to defining a new type of Human with the People type. Note that this is a new type, not inheritance in C# . Therefore, if there is a Move function in People, the Human object cannot call this Move function. If you must use it, you need to cast it. (The mandatory type conversion in Go is type + (), such as the above example Human(People) can force the People type to Human type)

  • Define type aliases
type Human = People

If the equal sign is used for definition, it is equivalent to defining an alias Human for the type People. In this case, the code Human in People can also be used normally. The above two usages are basically not commonly used, so we only need to understand them here.

2.2.4.Defer and finally

The defer in Go is the same as the finally in C#. There is only one thing that can be done before a method exits. Unlike C#, the defer statement in Go does not have to be written at the end. For example, we often see code in this style:

var mutex sync.Mutex // 一个全局锁,可以类似的等价于C#中的Monitor类

func do() {
    
    

mutex.Lock()

defer mutex.Unlock()

// ...

}

The above example means to define a global lock, lock it when the do function enters, and unlock it when it exits. Then write your own business logic. In addition, multiple defers can also be written, but the final execution order is executed from bottom to top, that is, the last defined defer is executed first.

2.3Keywords that Go has but C# does not have

  • fallthrough
  • func

2.3.1. Fallthrough

This keyword is for compatibility with fallthrough in C language, and its purpose is to jump down a case in the switch-case statement, such as the following example:

switch n := "a"; n {
    
    

case n == "a":

fmt.Println("a")

fallthrough

case n == "b":

fmt.Println("b")

case n == "c":

fmt.Println("c")

}

The final output of this example is:

a

b
### 2.3.2.Func

Like other functions (such as function in JavaScript, def in Python), func in Go is used to define functions.

// 定义了一个函数名称为getName的函数

// 其中包含一个int类型的参数id

// 以及两个返回值,string和bool类型

func getName(id int) (string, bool) {
    
    

return "jeffery", true

}

In functions in Go and a series of other syntaxes that require type definitions, the name always follows the type . In addition, func in Go can also be used with type to define delegates in C#. For example, we can define a .Net Core middleware in C#:

public delegate void handleFunc(HttpContext httpContext);

public delegate handleFunc middleware(handleFunc next);

Such code can be implemented in Go like this:

type handleFunc func(httpContext HttpContext)

type middleware func(next handleFunc) handleFunc

3. Extended link

How to import/export Excel XLSX in front-end browser using Blazor framework

Everything can be integrated series: low-code docking WeChat applet

C# write server-side API

Guess you like

Origin blog.csdn.net/powertoolsteam/article/details/131246989