preface
Go (also known as Golang) is a statically strongly typed, compiled language developed by Robert Griesemer, Rob Pike, and Ken Thompson of Google. The syntax of Go language is similar to THAT of C, but it has the following functions: memory safety, garbage collection, structure and cSP-style concurrent calculation.
Tips: Because this article is basic, it is suitable for front-end development engineers who are interested in Go and JAVA development engineers who have not been exposed to this language. This is a very young language, so I hope this article gives you an idea of the basic gameplay of Go. It would be nice if we could still have fun.
Learn Go for the first time
features
- Simple, fast and safe
- Parallel, fun, open source
- Memory management, array security, fast compilation
use
- Server programming
- Distributed systems, database agents, middleware
- Network programming, Web applications, API applications, download applications
- Database operations
- Developing the cloud Platform
Environmental installation
Supported systems:
- Linux
- FreeBSD
- Mac OS
- Windows
Install it on a Mac system
- Download the binary package: go1.15.Darwin-amd64.tar.gz
- Decompress the downloaded binary package to
/usr/local
directory
tar -C /usr/local -xzf go115..darwin-amd64.tar.gz
Copy the code
- will
/usr/local/go/bin
Add directories to the PATH environment variable:
export PATH=$PATH:/usr/local/go/bin
Copy the code
Note: On MAC, you can double-click the.pkg installation package in /usr/local/go/ to install it
Install it in Windows
Then talk about Windows platform, Windows system can directly download go1.15.Windows-amd64. msi to install. (In the installation package window, click Next continuously)
By default, the installation files are installed in the C:\Go directory.
To create a new test.go file, enter the following sample code:
/* test.go */
package main
import "fmt"
func main(a) {
fmt.Println("Hello, World!")}Copy the code
The command line execution code output is as follows:
Microsoft Windows [Version10.018363.959.]
(c) 2019Microsoft Corporation. All rights reserved. D:\Workspace>go run test.go
Hello, World!
Copy the code
The language structure
Basic components of Go:
- Package declaration
- Introduction of package
- function
- variable
- Statement & expression
- annotation
Take a look at the various parts of Test.go:
package main
Defines the package name. You must specify which package the file belongs to in the first non-comment line of the source file, as in:package main
.import "fmt"
Tell the Go compiler that the program needs to be usedfmt
Package (function, or other element),fmt
The package implements formattingIO
Function of (input/output).func main()
Is the function that the program starts executing. The main function is required by every executable program, and is generally the first function to be executed after startup (if any)init()
Function executes the function first.fmt.Println("Hello, World!" )
You can print a string to the console.- When an identifier (including constants, variables, types, function names, structure fields, and so on) begins with a capital letter, such as:
Group1
, then objects using this form of identifier can be used by the code of the external package (the client program needs to import the package first), which is called an export (as in object-oriented languages)public
); Identifiers that begin with a lowercase letter are not visible outside the package, but they are visible and available throughout the package (as in object-oriented languages)protected
).
The data type
type | describe |
---|---|
The Boolean | Boolean values can only be constantstrue orfalse . A simple example:var b bool = true . |
Numeric types | The integerint And floating-pointfloat32 ,float64 , Go language supports integer and floating point numbers, and supports complex numbers, where the operation of bits using complement code. |
String type | A string is a sequence of characters of fixed length joined together. The Go string is concatenated by a single byte. Go language string used in bytesUTF-8 Coding identificationUnicode The text. |
The derived type | These types include Pointer, array, struct, Channel, function, slice, interface, and Map |
variable
The Go language variable name consists of letters, digits, and underscores (_). The first character cannot be a digit.
A common form of declaring variables is to use the var keyword.
Variable declarations
Specifies the type of the variable, which defaults to zero if not initialized.
package main
import "fmt"
func main(a) {
/* Declare a variable and initialize */
var a = "hello"
fmt.Println(a) /* hello */
/* Zero if not initialized */
var b int
fmt.Println(b) /* 0 */
/* bool Zero is false */
var c bool
fmt.Println(c) /* false */
}
Copy the code
You can also determine your own variable type based on the value.
package main
import "fmt"
func main(a) {
var d = true
fmt.Println(d) /* true */
}
Copy the code
If you do not declare a new variable on the left, you will get a compilation error.
package main
import "fmt"
func main(a) {
f := "hello" /* var f string = "hello" */
fmt.Println(f)
}
Copy the code
Note: Only the reference (address) is copied when the variable type is a reference and there is an assignment (e.g., a = b).
Pointer to the
Variables are convenient placeholders used to refer to computer memory addresses.
The Go address is &, and when used before a variable, it returns the memory address of the variable.
package main
import "fmt"
func main(a) {
var a int = 100
fmt.Printf("Variable memory address: %x\n", &a )
}
/ * o * /Memory address of the variable: C000010080Copy the code
What is a pointer
A pointer variable points to the memory address of a value.
var ip *int /* points to an integer */
var fp *float32 /* points to floating point */
Copy the code
How to use Pointers
Use process:
- Defining pointer variables
- Assign to a pointer variable
- Access the value in a pointer variable that points to an address
The pointer type is preceded by an asterisk (prefix) to get what the pointer points to.
package main
import "fmt"
func main(a) {
var a int = 10 /* Declare the actual variable */
var ip *int /* Declare a pointer variable */
ip = &a /* The storage address of the pointer variable */
fmt.Printf("The address of variable A is: %x\n", &a )
/* The storage address of the pointer variable */
fmt.Printf("IP variable stored pointer address: %x\n", ip )
/* Use Pointers to access values */
fmt.Printf("* IP variable value: %d\n", *ip )
}
/ * o * /C000010080 address of the pointer to the IP variable:10
Copy the code
Null pointer
When a pointer is defined without assigning any variables, its value is nil.
Nil Pointers are also called null Pointers.
Nil is conceptually the same as null, None, nil, and null in other languages.
A pointer variable is usually abbreviated to PTR.
The structure of the body
Arrays can store the same type of data in Go, but in structures we can define different data types for different items.
A structure is a collection of data with the same or different types of data.
Defining structure
Structure definitions require the use of type and struct statements. Struct statements define a new data type that has one or more members in the structure. The type statement sets the name of the structure.
Example:
package main
import "fmt"
type Games struct {
name string
url string
class string
game_id int
}
func main(a) {
// Create a new structure
fmt.Println(Games{League of Legends."https://lol.qq.com/main.shtml"."MOBA".666666})
// The key => value format can also be used
fmt.Println(Games{name: League of Legends, url: "https://lol.qq.com/main.shtml", class: "MOBA", game_id: 666666})
// Fields ignored are 0 or empty
fmt.Println(Games{name: League of Legends, url: "https://lol.qq.com/main.shtml"})}/ * o * /{league of Legends HTTPS://lol.qq.com/main.shtml MOBA 666666}{league of Legends HTTPS://lol.qq.com/main.shtml MOBA 666666}{league of Legends HTTPS://lol.qq.com/main.shtml 0}
Copy the code
Access structure members
To access a structure member, use the dot. Operator of the form:
Struct. member nameCopy the code
Example:
package main
import "fmt"
type Games struct {
name string
url string
class string
game_id int
}
func main(a) {
var LOL Games /* declare LOL as Games */
/* LOL description */
LOL.name = League of Legends
LOL.url = "https://lol.qq.com/main.shtml"
LOL.class = "MOBA"
LOL.game_id = 666666
/* Print the LOL message */
fmt.Printf( "LOL name : %s\n", LOL.name)
fmt.Printf( "LOL url : %s\n", LOL.url)
fmt.Printf( "LOL class : %s\n", LOL.class)
fmt.Printf( "LOL game_id : %d\n", LOL.game_id)
}
/ * o * /LOL name: LOL url://lol.qq.com/main.shtml
LOL class : MOBA
LOL game_id : 666666
Copy the code
Structure pointer
If you want to change the contents of the result body data inside a function, you need to pass in a pointer:
package main
import "fmt"
type Games struct {
name string
url string
class string
game_id int
}
func changeGame(game *Games) {
game.name = "The Chess of Genting"
}
func main(a) {
var LOL Games
LOL.name = League of Legends
LOL.url = "https://lol.qq.com/main.shtml"
LOL.class = "MOBA"
LOL.game_id = 666666
changeGame(&LOL)
fmt.Println(LOL)
}
/ * o * /{genting chess HTTPS://lol.qq.com/main.shtml MOBA 666666}
Copy the code
Slice
Go slicing is an abstraction of arrays.
The length of Go arrays cannot be changed, and such collections are not suitable for certain scenarios. Go provides a flexible and powerful built-in type slice (” dynamic array “). Compared with arrays, the length of slices is not fixed, and you can append elements, which may increase the size of slices.
Definition section
/* Declare an array of unspecified size to define slices */
var identifier []type
/* Use the make() function to create slices */
var slice1 []type = make([]type.len)
/ * shorthand * /
slice1 := make([]type.len)
/* You can also specify the capacity. The capacity parameter is optional */
make([]T, length, capacity)
Copy the code
Here len is the length of the array and also the initial length of the slice.
Slice initialization
s :=[] int {1.2.3}
Copy the code
Directly initialize the slice, [] indicates the type of slice, {1,2,3} initialization values are 1,2,3 in sequence. This cap = len = 3
s := arr[:]
Copy the code
Initialize slice s, which is a reference to array arr
s := arr[startIndex:endIndex]
Copy the code
Create a new slice of the arR from the elements under subscript startIndex to endIndex-1
s := arr[startIndex:]
Copy the code
Change the arR from startIndex to the last element (default endIndex case)
s := arr[:endIndex]
Copy the code
Will represent the beginning of the first element of arR (the default startIndex case) to the element under the subscript endIndex
s1 := s[startIndex:endIndex]
Copy the code
Section S1 is initialized by section S
s :=make([]int.len.cap)
Copy the code
The built-in function make() initializes the slice S, identified by []int as the slice whose element type is int
Len () and cap() functions
Slices are indexable and the length can be obtained by the len() method.
Slicing provides a method for calculating capacity. Cap () can measure how long a slice can reach.
package main
import "fmt"
func main(a) {
var numbers = make([]int.3.10)
printSlice(numbers)
}
func printSlice(x []int){
fmt.Printf("len=%d cap=%d slice=%v\n".len(x),cap(x),x)
}
/ * o * /
len=3 cap=10 slice=[0 0 0]
Copy the code
Range
The range keyword in Go is used to iterate over elements of an array, slice, channel, or map in a for loop. It returns the index of the element and its value in arrays and slices, and key-value pairs in collections.
package main
import "fmt"
func main(a) {
/* This is where we use range to sum a slice. Using arrays is similar to this */
nums := []int{1.2.3}
sum := 0
for _, num := range nums {
sum += num
}
fmt.Println("sum:", sum)
/* Using range on an array passes in the index and value variables. In the example above we do not need to use the ordinal of the element, so we omit the "_" whitespace. Sometimes we do need to know its index */
for i, num := range nums {
if num == 3 {
fmt.Println("index:", i)
}
}
/* range can also be used in map key-value pairs */
kvs := map[string]string{"a": "apple"."b": "banana"}
for k, v := range kvs {
fmt.Printf("%s -> %s\n", k, v)
}
/* range can also be used to enumerate Unicode strings. The first argument is the index of the character, and the second is the character itself (the Unicode value) */
for i, c := range "go" {
fmt.Println(i, c)
}
}
/ * o * /
sum: 6
index: 2
a -> apple
b -> banana
0 103
1 111
Copy the code
Map (Set)
A Map is an unordered collection of key-value pairs. One of the most important aspects of a Map is its ability to quickly retrieve data through keys, which are similar to indexes that point to the value of the data.
A Map is a collection, so we can iterate over it in the same way we iterate over arrays and slices. However, the Map is unordered and we cannot determine its return order because the Map is implemented using a hash table.
Define the Map
A map can be defined using either the built-in function make or the map keyword:
/* Declare variables, default map is nil */
var map_variable map[key_data_type]value_data_type
/* Use make function */
map_variable := make(map[key_data_type]value_data_type)
Copy the code
If the map is not initialized, a nil map is created. Nil maps cannot be used to hold key-value pairs
The following example demonstrates creating and using a map:
package main
import "fmt"
func main(a) {
var cnNameMap map[string]string /* Create a collection */
cnNameMap = make(map[string]string)
/* map inserts key-value pairs, each English corresponding Chinese name */
cnNameMap [ "Ashe" ] = "Ice Shooter Ash."
cnNameMap [ "Annie" ] = "Annie the Dark Girl."
cnNameMap [ "Alistar" ] = "Bull Chief Arista."
cnNameMap [ "Twisted" ] = "The Card master Treaster."
/* Use key to output Chinese name */
for cn := range cnNameMap {
fmt.Println(cn, "The Chinese name is", cnNameMap [cn])
}
/* Check if the element exists in the collection */
name, ok := cnNameMap [ "Sivir" ] /* if true, it exists, otherwise it does not exist */
/* fmt.Println(name) */
/* fmt.Println(ok) */
if (ok) {
fmt.Println("Sivir's Chinese name is.", name)
} else {
fmt.Println("Sivir's Chinese name does not exist.")}}/ * o * /Annie is the daughter of Darkness, Annie Alistar is Twisted and the Chinese name of Twisted is Twisted and the Chinese name of Ashe is Cold Archer and Ashsivir does not existCopy the code
The delete () function
The delete() function is used to delete the elements of the collection, taking a map and its corresponding key.
Examples are as follows:
package main
import "fmt"
func main(a) {
/* Create map */
cnNameMap := map[string]string{
"Annie": "Annie the Dark Girl."."Alistar": "Bull Chief Arista."."Twisted": "The Card master Treaster."."Ashe": "Ice Shooter Ash."."Sivir": "The Goddess of War sewell.",
}
fmt.Println(League of Legends)
/* Print the Chinese name */
for cn := range cnNameMap {
fmt.Println(cn, "The Chinese name is", cnNameMap [ cn ])
}
/* Delete the element */ delete(cnNameMap, "Alistar")
fmt.Println("Bullhead Chief Arista has been removed.")
fmt.Println("League of Legends after removing elements.")
/* Print the Chinese name */
for cn := range cnNameMap {
fmt.Println(cn, "The Chinese name is", cnNameMap [ cn ])
}
}
/ * o * /League of Legends Annie is the daughter of Darkness and Alistar Twisted is a Twisted card master and Ashe is a cold Archer and Sivir is the goddess of war and The bullheaded Chief and Alistar has been deleted After removing the elements, league of Legends is named Ashe and his Chinese name is Ice Archer Β· Ashsivir and his Chinese name is The goddess of War Β· Sewell. Annie and her Chinese name is daughter of Darkness Β· Annie Twisted and her Chinese name is card master Β· TwistCopy the code
Type conversion
Type conversion is used to convert a variable of one data type to a variable of another type. The basic format of Go language type conversion is as follows:
Type (expression)
The following example converts an integer to a floating-point type
package main
import "fmt"
func main(a) {
var sum int = 10
var count int = 3
var mean float32
mean = float32(sum)/float32(count)
fmt.Printf("Mean = %f\n",mean)
}
/ * o * /The value of mean is:3.333333
Copy the code
interface
The Go language provides another data type, the interface, which defines all common methods together, and any other type that implements those methods implements the interface.
package main
import (
"fmt"
)
type Phone interface {
call()
}
type AndroidPhone struct{}func (androidPhone AndroidPhone) call(a) {
fmt.Println("I am Android, I can call you!")}type IPhone struct{}func (iPhone IPhone) call(a) {
fmt.Println("I am iPhone, I can call you!")}func main(a) {
var phone Phone
phone = new(AndroidPhone)
phone.call()
phone = new(IPhone)
phone.call()
}
/ * o * /
I am Android, I can call you!
I am iPhone, I can call you!
Copy the code
In our example, we define an interface called Phone with a method called Call (). We then define a Phone type variable in the main function and assign the values AndroidPhone and IPhone respectively.
Error handling
The Go language provides a very simple error handling mechanism through a built-in error interface.
The error type is an interface type, and this is its definition:
type error interface {
Error() string
}
Copy the code
The function usually returns an error message in the final return value. Errors. New returns an error message:
func Sqrt(f float64) (float64, error) {
if f < 0 {
return 0, errors.New("math: square root of negative number")}}Copy the code
Example:
package main
import "fmt"
/* Define a DivideError structure */
type DivideError struct {
dividee int
divider int
}
/* Implements the error interface */
func (de *DivideError) Error(a) string {
strFormat := ` Cannot proceed, the divider is zero. dividee: %d divider: 0 `
return fmt.Sprintf(strFormat, de.dividee)
}
/* The function that defines the division operation of type 'int' */
func Divide(varDividee int, varDivider int) (result int, errorMsg string) {
if varDivider == 0 {
dData := DivideError{
dividee: varDividee,
divider: varDivider,
}
errorMsg = dData.Error()
return
} else {
return varDividee / varDivider, ""}}func main(a) {
/* Normal */
if result, errorMsg := Divide(100.10); errorMsg == "" {
fmt.Println("100/10 =", result)
}
/* Returns an error message */ when the divisor is zero
if _, errorMsg := Divide(100.0); errorMsg ! ="" {
fmt.Println("errorMsg is: ", errorMsg)
}
}
/ * o * /
100/10 = 10
errorMsg is:
Cannot proceed, the divider is zero.
dividee: 100
divider: 0
Copy the code
concurrent
The Go language supports concurrency, so all you need to do is open Goroutine with the Go keyword.
Goroutine is a lightweight thread, and goroutine scheduling is managed by the Golang runtime.
Such as:
go f(a, b, c)
Open a new Goroutine:
f(a, b, c)
All goroutines in the same program share the same address space.
package main
import (
"fmt"
"time"
)
func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
func main(a) {
go say("hi")
say("hello")}/ * o * /
hi
hello
hello
hi
hello
hi
hello
hi
hello
Copy the code
Refer to the article
- Go Language Tutorial
Thank you
- This paper makes a preliminary introduction to Go language, hoping to play a role.
- If there are any errors in this article, please correct them in the comments section.
- If this article helped you, give it a thumbs up! Thanks for reading.
π technology project phase ii | and I Go those things…