Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Go language

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "how to use Go language". Friends who are interested may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use the Go language.

Overview of Go

Characteristics of Go

I often say that if I want to learn something, I must first find out why it appears. What problem has been solved?

As long as you understand the underlying problems at the bottom, you will have the continuous motivation to learn in depth, rather than blindly following the trend and three minutes of heat.

The Go language is a project released by google in November 2009. it is a very young man in the programming language.

As for the birth and history of the Go language, you can take a look at this article: three minutes to learn about the past and present lives of the Go language.

Personally, I think the birth of Go has the necessity of the times, because its main solution is to solve:

Performance and weak typing of dynamic languages

The efficiency and complexity of static language development, as well as the concurrency problem

We all know that Google is the company with the largest amount of data in the world. The lightweight thread design of the Go language also helps Google reduce the cost of computing and concurrent computing, which is also an important purpose for the birth of the Go language.

In today's data explosion, the Go language rebalances development efficiency and performance, so Go will be the most important programming language in the next decade.

Regarding the positioning of go, it may be clearer if you look at the following picture:

The Design concept of Go

When you first come into contact with this language, you can feel that its designers have thought carefully, and developers who have migrated from different languages can see the shadow of many other languages in Go, because designers have borrowed from the designs of many other languages, but it is also very restrained, not completely copied, and very accurately integrate excellent and used designs into Go. Many impractical and complex designs are eliminated directly.

Although Go comes from a famous family, you don't see any academic shadow in Go, no superfluous design, no complex concepts, simple, practical design ideas that can be seen everywhere, because its creators' ideas are:

Only through the simplicity of design can the system maintain stability and self-consistency in the process of growth.

Another feature of Go that is different from other languages is that Go may be the first language to impose code style at the compiler level in order to pursue code readability. For example:

The first capital letter stands for public and represents the export type, which can be accessed externally

The initials lowercase code private, which represents a non-exported type and can only be accessed internally

There are also restrictions on {} line wrapping

Useless variables are not allowed at the compilation level.

Wait a minute &.

Go for dynamic languages:

For developers who have written dynamic languages similar to Ruby,Python, the biggest headache should be the type problem, because the type is uncertain, so many problems cannot be found at compilation time and can only be exposed when they are directly runtime, and the processing cost is extremely high. Go language provides a simple and sufficient type system, which does not have much hand cost for dynamic language developers, and also helps dynamic language developers to solve most type problems.

Go for static languages:

Go language does not copy the super-complex type system of C++ and Java. Go abandons a large number of OOP features and does not support inheritance and overloading. For mainstream OOP programming languages such as Java/C++, Go may also be a complete anomaly, but do not doubt that Go is also an object-oriented programming language, but he is using his own understanding method, an unusual way to explain object-oriented, its characteristics are as follows:

It has no inheritance, not even classes.

There is no inheritance, but the inheritance is accomplished by combination.

Types and interfaces are non-intrusive (there is no need to declare the implementation of the interface)

As for the differences between other languages of Go, you can list a separate article, which will not be discussed in depth for the time being.

Introduction to Go Grammar

Short assignment statement, incremental statement

In line with the habits of Java programmers, Go supports short assignment statements and incremental statements. Here is a simple example:

X: = 0x+ = 5 fmt.Print (x) / / x = 5xrays + fmt.Print (x) / / x = 6xmuri-fmt.Print (x) / / x = 5

Although Go is a statically compiled language, it has many grammatical features unique to dynamic languages, such as batch assignment, variable exchange, and examples:

/ / batch assignment x, y, z: = 1, 2, 3 / / Exchange variables x, y = y, x

Java programmers should envy this way of exchanging variables, because if you want to exchange variables in Java, you have to declare a very awkward tmp temporary variable in order to exchange variables.

Go only supports for as a circular statement (reducing mental burden)

/ / for format for init; condition; post {/ / Circular Logic} for I: = range ary {/ / for range Shortcut method for traversing slice} initial experience

Go naming convention

Unlike other languages, functions, variables, constants, types, and packages in Go follow a simple and unified principle:

The name starts with a Unicode character and is case sensitive

For example, HeapSort and heapSort are different names

Also, as mentioned above, the keywords declared by private and public, which are not very useful, are directly removed through the naming rules of uppercase and lowercase. This kind of subtraction without changing the function can be described as fast, accurate and ruthless.

In addition, according to the official Demo and documentation of Go, Go advocates the principle of short naming, which has the following two points:

The longer the scope, the clearer the naming should be (that is, the longer)

Go advocates the naming of humps, not the underscore segmentation in C language.

Keyword

Let's first look at a set of data comparisons:

The number of C++ keywords is 62

The number of Java keywords is 53

Number of Go keywords 25

From the number of keywords, we can also see the restraint of the designers of Go language and the practice of simple design philosophy. It also reduces the cost of learning and the mental burden of learning Go. It is a very friendly language for beginners.

Variable expression

To sum up, there are actually only four declarable types of Go, mainly as follows:

Variables: declared via var or: =

Constants: declared by keyword const

Type: declared by keyword type

Function: declared by keyword func

The standard declaration format for variables is:

Var name type = expression / / the above declaration is very clear, but very verbose, and it is rarely used at ordinary times. The declaration format of short variables / / is usually used as follows: name: = expression / / short variables can automatically deduce the type of name through expression

The format of short variable declaration is short and flexible, so it is a common way of declaration.

In addition, in the Go language, variables and constants can be declared in batches in the following ways:

Var (...) Const (...)

If the variable does not initialize the expression, such as var name int, then it will trigger the zero mechanism of the Go language (Default Value). You can Google the zero value of each type, so we won't talk at length here.

Through the zero value, we can understand that there are no uninitialized variables in Go, which also ensures the robustness of Go language and is not prone to low-level errors.

Reference passing and value passing

Anyone familiar with the basics of the Go language knows that the reference passing of Go defaults to value passing without any modifiers, so why should it be designed this way?

Because this design will improve the performance of garbage collection in Go language, value transfer can minimize the escape behavior of variables, variables will be assigned to the stack with the greatest probability, the variables assigned on the stack do not need to wait for GC collection, and can also reduce heap memory consumption and GC pressure, not to ask everyone to learn how garbage collection works, or to pay special attention to the escape behavior of variables. But it is important to understand the life cycle of the variable.

It is well known that the pointer to the variable can be obtained through the & variable of the expression in Go, and the value of the pointer variable can be obtained through * pointer, so it is easy to pass a reference in Go, and the pointer can be used to read and update variables without knowing the name of the variable.

Pointers can be compared, pointers of the same value must be the same, let's look at a piece of code:

P: = 0 / / declare type & p! = nil / / true, compare pointers, indicating that p currently points to a variable var x, y int / / declaring type, default value 0 & x = = & x / / true, the same pointer must be equal & x = & y / / false, different pointers lead to different results

Function parameters can also be used to indicate the passing type of the current parameter through *. For example, function: func incr (p * int) indicates that the current p parameter is passed by a pointer, but from years of programming experience, if too many references are passed, it may be difficult to find and locate when your library is large, or if you want to find out where a frequently passed reference variable has been modified. This may be a side effect of passing pointers.

Basic type

There are also few basic types of Go, which are commonly used: integer (int), floating point (flora), Boolean (bool), string (string), plural (complex). The difference with Java is that string is a built-in basic data type in Go and is indeed an entity class in Java. But I personally feel that String is supposed to be a basic data type. It seems awkward to use class composition byte [] to implement strings.

Integer number

Here we mainly distinguish signed integers from unsigned integers.

However, unsigned cannot express negative numbers, so it is rarely used in common use. It is often only used for database self-increment ID, bit operation and specific arithmetic, bit set, parsing binary, and so on. Here, it is better to use more signed integers such as int. The specific distinction is as follows:

Signed integers: int8, int16, int32, int64

Unsigned integers: uint8, uint16, uint32, uint64

The number after Int represents the size of the type, that is, the 2N power, using a clear type can make better use of memory space, Go language all binary operators and other languages are no different, in addition Go does not support ternary expressions, I do not know why, personal guess may be due to considering the function return value of the reason, but if/else such code to write a lot, feel very nauseous.

Floating-point numbers float32 and float64 have nothing to say, they are all very simple. There is only one principle. If you want to reduce the error of floating-point operation, float64 is recommended as far as possible, because the float64 valid number is 15 digits, which is almost 3 times that of float32.

The plural (complex) seems to be rarely used at the moment. I'll talk about it later.

Boolean type (bool) is basically the same as other languages except for its short name. Skip

String

You can talk about it briefly. String is the basic data type of Go, which is a little different from the type of Java, but there are many similarities, such as:

Strings can be concatenated with a plus sign (+), but a new string is returned (but used with performance sensitivity)

I don't know if the designer of Go language is also the designer of UTF-8 coding (Rob, Ken), so the source file of Go language is UTF8 encoding by default. It can be predicted that using Go language will greatly reduce the problem of garbled code.

In addition, several toolkits for dealing with characters commonly used in Go are introduced, as follows:

Strings: provides commonly used character operation functions such as search, comparison, replacement, etc.

Bytes: as the name implies, it provides functions that manipulate the byte [] type.

Strconv: provides services that convert Boolean, integer, floating point, and other types to string

Unicode: provides a functional service for judging the characteristics of text symbols

Named return value

The Go language can name the return value in the return type, so there is no need to display the return in return. The code is as follows

Func split (sum int) (x, y int) {x = sum + 3 y = sum + x return / / return the variable directly} func main () {fmt.Println (split (50)) / / res:53, 103}

However, this flexible writing will affect the readability of the code and is not conducive to teamwork. It is not recommended.

From the point of view of code readability and teamwork, it is recommended to write it in the following way, and the code is more readable, as follows:

Func split (sum int) (int, int) {x: = sum + 3 y: = sum + x return x, y} func main () {fmt.Println (split (50)) / / res:53, 103}

Constant

It is worth noting that constants use the const keyword, and any basic data type can be declared as a constant, but not with: = syntax declaration, example:

Const Pi = 3.14const World = "World" const Truth = true

Similar to import, you can declare in batches, which reduces a lot of repeated declarations in const, as follows:

Const (Pi = 3.14 World = "World" Truth = true)

Cycle

There is only one for loop, and the simple usage is as follows:

Sum: = 0 for I: = 0; I

< 10; i++ { sum += i } Go语言的循环和 Java、Javascript 的区别主要在于没有小括号,但是大括号则是必须的 很多编程语言都有 while 语句,但是在 Go 里面也是可以用 for 替代,如下: sum := 1 for sum < 100 { sum += 1 // sum 累积 100 次 } // out: 100 if 跟 for 类似,if 也是没有小括号的,其他方面和常见的语言差不多,如下: if x < 0 { fmt.Println('x < 0') } 比较有特色的是,Go语言的 if 可以在执行表达式之前,执行一段声明语句,如下: func conditon(x, n, lim float64) float64 { // 初始化 v 变量,在进行表达式判定 // 值得注意的是:v 是 if 条件内的局部变量,外部无法调用 if v := x * n; v < lim { return v } return lim } condition(3, 5, 10) // out: 10 switch switch 是简化一连串 if else 的利器,不过 Go 语言的 switch 和其他语言差别不大,这里就不多说了。。 延迟函数 defer 算是 Go 语言的特色,Go 的语言运行机制保证它会在函数返回后执行,所以通常用于关闭资源(网络/文件/IO)等操作,如下: defer fmt.Println("end") // 最先声明,但会在最后执行 fmt.Println("hello") fmt.Println("Phoenix") //out: //hello //Phoenix //end 值得注意的是,在使用 defer 声明函数被压力栈中,所以有多个 defer 声明会根据 FIFO 先进先出的顺序执行,如下 defer fmt.Println("1") defer fmt.Println("2") defer fmt.Println("3") fmt.Println("done") // done // 3 // 2 // 1 指针 Go 通过 & 可以直接操作指针,并且通过 * 操作符可以通过指针修改引用值,如下: x, y = 100, 200 p := &x // get i 指针 *p = 21 // 通过指针修改引用值 fmt.Println(x) //out x = 21 slice 切片 是 Go 语言比较常用的动态数组,值得注意的是它的传递是引用的,任何对切出来的变量进行修改,都会影响到原本的值,代码如下: names := []string{ "金刚", "哥斯拉", "怪兽", "奥特曼" } a := names[0:2] // out:[金刚,哥斯拉] b := names[1:3] // out:[哥斯拉,怪兽] b[0] = "XXX" fmt.Println(a) // out:[金刚,XXX] fmt.Println(b) // out:[XXX,怪兽] fmt.Println(names)// out:[金刚,XXX,怪兽,奥特曼] 备注:声明一个 slice 就像声明一个没有长度的数组 slice 的快捷切片写法: s := []int{2, 3, 5, 7, 11, 13} s = s[1:4] // out: 3, 5, 7 // s[0:2] 的简写 s = s[:2] // out: 3, 5 s = s[1:] // out: 5 在 slice 中 length 和 capacity 是分开存储,例如上面改变长度,并不会改变容量,在 slice 中的长度和容量可以通过函数 len() 和 cap() 获取,参考以下几行代码: s := []int{2, 3, 5, 7, 11, 13} // len=6, cap=6 s = s[:0] // len=0, cap=6 s = s[:4] // len=4, cap=6 Map Go 语言 map 的简单用法: // 使用字面量,声明并且初始化一个简单的 map,[key:string,value:int] s := map[string]int{"a": 123, "b": 456, "c":789} // out: map[a:123 b:456 c:789] // 插入和更新 s["d"] = 1001 // out: map[a:123 b:456 c:789, d:1001] //删除元素 delete(s, "d") // out: map[a:123 b:456 c:789] // 检索元素 value = s["a"] // out: 123 // 比较常用的快捷检索 if v, ok := s["a"]; ok { fmt.Println("the value is >

", v) / / out: 123}

Function variable

In Go, functions can be copied as variables or referenced as parameters.

/ / declare the function argument as a function variable, and fn executes the function func compute (fn func (float64, float64) float64) float64 {return fn (3,4)} / / declare the function variable hypot: = func (x, y float64) float64 {return math.Sqrt (x, y float64)} / / transfer function variable hypot (5,12) / / out: 13 compute (hypot) / / out: 5

Closure

The closure of Go is an anonymous function and can access external local variables. The following adder returns a function closure:

Func adder () func (int) int {sum: = 5 return func (x int) int {sum + = x return sum}} / / declare pos function variable pos: = adder () fmt.Println (pos (5)) / / out: 10 so far, I believe you have a deeper understanding of "how to use Go language". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report