Why Go

  • C-like syntax, which means Java, C#, and JavaScript programmers can pick it up quickly
  • Have their own garbage collection mechanism
  • Cross-platform, compilable execution without installation dependencies
  • Support the reflection

Introduction to Go

Go, or Golang, originated in 2007 and was officially released in 2009. Go is a very young language whose primary goal is to “combine the speed of a dynamic language like Python with the performance and security of a compiled language like C/C++.”

The data type

The data type instructions
bool Boolean
string string
int uint8,uint16,uint32,uint64,int8,int16,int32,int64
float float32,float64
byte byte

Reference: www.runoob.com/go/go-data-…

The basic grammar

HelloWorld

Online running example: play.golang.org/p/-4RylAqUV…

package main

import "fmt"

var name string

func init(a) {
  name = "world"
}

func main(a) {
  fmt.Println("hello " + name)
}
Copy the code

Let’s execute:

$ go run main.go # main.go is the name of the file you just created
$ hello world
Copy the code

variable

Variable declarations

Example: running play.golang.org/p/zPqCkRZgr…

package main

import (
	"fmt"
)

func main(a) {
	var name string   / / declare
	name = "da'mao'mao" / / assignment
	fmt.Println(name)

	var age int = 18 // Declare and assign
	fmt.Println(age)
}
Copy the code

Type inference

Example: running play.golang.org/p/0My8veBvt…

package main

import (
	"fmt"
)

func main(a) {
	name := "damaomao"
	fmt.Println(name)

	age := 18
	fmt.Println(age)
}
Copy the code

function

  • A function can have multiple return values
  • Implicitly specifies whether a function is private or public, uppercase public and lowercase private
  • There is nothing like Javatry cache,throwThe Go language is passed through willerrorHandle exceptions as return values.
  • Overloading not supported

We understand, through an example below online run the example: play.golang.org/p/PYy3ueuPF…

package main

import (
	"errors"
	"fmt"
	"strconv"
)

func main(a) {
	log1()

	log2("hello world")

	ret1 := add1(1.1)
	fmt.Println("add1 result:" + strconv.Itoa(ret1))

	ret2, err := Add2(0.1)
	if err == nil {
		fmt.Println("Add2 result:" + strconv.Itoa(ret2))
	} else {
		fmt.Println("Add2 error", err)
	}
}

// Private, no entry, no return value
func log1(a) {
	fmt.Println("execute func log1")}// Private, input, no return value
func log2(msg string) {
	fmt.Println("execute func log2:" + msg)
}

// Private, two input parameters, one return value
func add1(count1, count2 int) int {
	total := count1 + count2
	fmt.Println("execute func add3, result=" + strconv.Itoa(total))
	return total
}

Public, two input parameters, multiple return values
func Add2(count1, count2 int) (int, error) {
	if count1 < 1 || count2 < 1 {
		return 0, errors.New("The quantity cannot be less than one.")
	}
	total := count1 + count2
	return total, nil
}
Copy the code

The output of this example is:

execute func log1
execute func log2: Hello world execute func add3, result=2 add1 result:2 Add2 The number of errors cannot be less than 1Copy the code

But when a function has multiple return values, sometimes you only care about one return value, in which case you can assign the other return values to the whitespace: _, as follows:

_, err := Add2(1.2)
iferr ! =nil {
  fmt.Println(err)
}	
Copy the code

Whitespace is special because the return value is not actually assigned, so you can assign different types of values to it without giving an error.

The structure of the body

Go is not an object-oriented language like Java. It has no concepts of objects and inheritance. There is no concept of class. In Go, there is a concept called struct, and structs are similar to Classes in Java. Let’s define a structure:

type User struct {
	Name   string
	Gender string
	Age    int
}
Copy the code

Above we define a structure User and give it three public properties: Name/Gender/Age. Now we create a User object.

user := User{
	Name:   "hahaha",
	Gender: "Male",
	Age:    18.// It is worth mentioning that the last comma is necessary, otherwise the compiler will report an error. This is one of the design philosophies of GO, which requires strong consistency.
}
Copy the code

Struct properties can be declared directly in a struct body. How to declare functions (methods in Java) for a struct body is as follows:

package main

import "fmt"

type User struct {
	Name   string
	Gender string
	Age    int
}

// Define a member method of User
func (u *User) addAge(a) {
	u.Age = u.Age + 1
}

func main(a) {
	user := User{
		Name:   "Hello"./ / name
		Gender: "Male"./ / gender
		Age:    18.// It is worth mentioning that the last comma is necessary, otherwise the compiler will report an error. This is one of the design philosophies of GO, which requires strong consistency.
	}
	user.addAge()
	fmt.Println(user.Age)
}
Copy the code

Pointer type and value type

In Java, both value types and reference types are fixed. Int, double, float, long, byte, short, char, Boolean are value types. The rest are reference types.

In Go:

  • &To fetch an address, let’s say you have a variableathen&aIs variableaThe address in memory is also typed for the Golang pointer, for example if a is a string then ampersand a is a pointer to a string called ampersand string in Go.
  • *So, for the value, let’s say, in the example above, you defineb := &aIf you printb, so the output is&aThe memory address of the*b

This example, we’ll look at the online operation: play.golang.org/p/jxAKyVMjn…

package main

import (
	"fmt"
)

func main(a) {
	a := "123"Println(a) fmt.println (b) fmt.println (*b)}123
0x40c128
123
Copy the code

Concurrent programming

Go’s concurrency is based on a Goroutine, which is similar to, but not a thread. You can think of a Goroutine as a kind of virtual thread. The Go language runtime participates in scheduling goroutines and allocating goroutines to each CPU to maximize CPU performance.

The Go program starts with the main() function of the main package, and creates a default Goroutine for the main() function when the program starts.

Let’s take a look at an example (online demo: play.golang.org/p/U9U-qjuY0…

package main

import (
	"fmt"
	"time"
)

func main(a) {
	// Create a goroutine
	go runing()
	// Create an anonymous goroutine
	go func(a) {
		fmt.Println("喜特:" + time.Now().String())
	}()

	If the main method is finished, all goroutines created by the main program will exit
	time.Sleep(5 * time.Second)
}

func runing(a) {
	fmt.Println(Method: "" + time.Now().String())
	time.Sleep(3* time.second)}2009- 11- 10 23:00:00 +0000 UTC m=+0.000000001Xi:2009- 11- 10 23:00:00 +0000 UTC m=+0.000000001
Copy the code

The results show that the sleep three seconds in fuck does not affect the output of the Fuck function.

If Goroutine is the concurrency of Go programs, then channel is the communication mechanism between them. A channel is a communication mechanism that allows one Goroutine to send value messages to another. Each channel has a special type, which is the type of data a channel can send. A channel that can send data of type int is written as chan int.

Here we use goroutine + channel to realize consumer model, a production sample code is as follows: (online execution: play.golang.org/p/lqUBugLdU…

package main

import (
	"fmt"
	"time"
)

func main(a) {
	// Create a channel
	channel := make(chan int64)

	// Asynchronous production
	go producer(channel)

	// Data consumption
	consumer(channel)
}

/ / producer
func producer(channel chan<- int64) {
	for {
		// Write data to the channel
		channel <- time.Now().Unix()
		// Sleep for 1 second
		time.Sleep(time.Second)
	}
}

/ / consumer
func consumer(channel <-chan int64) {
	for{timestamp := <-channel fmt.println (timestamp)}}1257894000
1257894001
1257894002
1257894003
Copy the code

Things that Java programmers find difficult to use

  • Exception handling
  • There is no generic
  • Polymorphism and overloading are not supported
  • Annotations are not supported (but attributes in his struct aretag)

reference

  • www.runoob.com/go/go-tutor…
  • Books.studygolang.com/the-little-…

Author’s brief introduction

Big Cat, the Internet company old code farmers, do not thrill uncomfortable sky, thousands of years of live server r & D and architecture experience.

  • Code farmers club: mlog.club
  • Follow the public account for more dry goods