This article was first published in the public number [programmer reading], welcome attention.

Go is the 21st century C language, with performance close to C/C++ and scripting languages (PHP,Javascript,Python) as easy to learn, backed by Google, a strong development team and an active community.

Features of the Go language

  • Grammar is simple
  • The language level supports concurrent programming
  • Cross-platform compilation
  • Own garbage collection mechanism

Go language statements do not require semicolons

package main 

import "fmt"

func main(){
    
    s := "hello world"
    
    fmt.Println(s)
}
Copy the code

The data type

Go is a strongly typed language, so when you declare a variable, you have to specify what type the variable is, right

Var I int = 10 b := 10 func Test(){s := 10 s := "Test"}Copy the code

PHP is a weakly typed programming language. You can declare a variable without specifying its type, but the variable can still be assigned to another type of value later

$a = 10;

$a = "test";
Copy the code

For, if, and switch

The condition body of the for, if, and switch statements does not require parentheses ()

for i := 0; i < 10; i++ {

}

i := 10

if i == 10 {

}
x := 10

switch x{
    
}
Copy the code

switch

  • Switch statement in PHP
$a = 10;
switch ($a) {
    case 10:
        echo "111";
        break;
    case 20:
        echo "222";
        break;
}

Copy the code

Switch statement of Go

func main() { var level string = "B" var score int = 90 switch score { case 90: level = "A" case 80: Case 50,60,70: level = "C" default: level = "D"} switch {case level == "A" : fmt.Printf(" excellent! \n") case level == "B", level == "C" : ftt. Printf(" good \n") Case level == "D" : ftt. Printf(" passable \n") case level == "F": FMT.Printf(" failing \n") default: FMT.Printf(" poor \n"); } FMT.Printf(" your grade is: %s\n", level); }Copy the code
  • Fallthrough keyword
Package main import "FMT" func main() {switch {case false: FMT.Println("1, case conditional statement false") fallthrough case true: Println("2, case conditional statement true") fallthrough case false: FMT.Println("3, case conditional statement false") fallthrough case true: Println("4, case conditional statement true") case false: FMT.Println("5, case conditional statement false") fallThrough default: Println("6, default case")}}Copy the code

cycle

Unlike other programming, the Go language does not support while or do… While, unlike PHP, which has foreach, Go loops only have for

  • General circulation
for i := 0; i < 10; i++ {

}
Copy the code
  • Traverse arrays, maps, or slices
for k,v := range arr {
    
    
}
Copy the code

Visibility of variables

In PHP, if you don’t use classes, you don’t have much visibility into variables; you declare global variables:

a.php

$a = 10;

Copy the code

b.php

include_once("a.php"); echo $a; / / output 10Copy the code

If you use a class, the members of a class, public,protected,private to distinguish the visibility of the members.

class A{
    
    public $a;
    
    private $b;
    
    protected $c;
    
}

class B extends A{
    
    
}
Copy the code

The Go language organizes the code in packages, and the visibility of variables is very simple, whether the first letter is capitalized and visible in packages and all visible

a.go

package my


var Username string = "test"

var age int = 20

const Test = "test"

const t = 123

Copy the code

b.go

package my


func GetUsername() string {
    return Username
}

func GetAge()int{
    return getAge()
}

func getAge()int{
    return a
}

Copy the code

main.go

package main import "my" import "fmt" func main(){ fmt.Println(my.Username) fmt.Println(my.GetUsername()) Fmt.println (my.getage ()) fmt.println (my.test) fmt.println (my.age)// error fmt.println (my.getage ())// error fmt.println (my.getage ())// error fmt.println (my.t)// error }Copy the code

Whether you need to compile

Go static compiled language, PHP dynamic scripting language

Because scripting languages need to be interpreted and executed by an interpreter, execution performs worse than compiled languages.

Function return value

The PHP language, like most data programming languages, supports only one return value for a function or method, whereas the Go language’s functions directly return multiple values.


func GetFile(path string)(file *os.File,err error){
    
    f,err := os.Open(path)
    
    return f,err
}

Copy the code

Blank identifier

Since declaring a variable without using it fails compilation, we can use a blank identifier when we receive multiple values from a function but don’t need them later.

func GetFile(path string) *os.File{
    
    file,_ := os.Open(path)
    
    return file
}
Copy the code

Character double quotation mark

The Go language does not support single quotation marks. In PHP, either single or double quotation marks are allowed.

  • PHP string
$a = '';
$b = ""
Copy the code
  • Go string
Var s string = "" // Double quotes must be usedCopy the code

A combination with Docker

The Go program ends up packaged as a binary file, which is usually very small, up to a few tens of megabytes, and we can package this binary file directly into the Docker image.

However, PHP projects cannot run without the file vendor, which stores all third-party libraries. This file may be very large, maybe hundreds of meters, so when DOCker is used to package PHP projects, the image will become very large.

Weird date formatting

  • PHP time and date formatting
$t = time(); / / Y: year, m: month, d: date, H: when I: minute, s: second echo date (" Y -m - d H: I: s ", $t);Copy the code
  • Go language time and date formatting
//2006: Year, 01: month, 02: date, 15/03: hour, 04: Minutes. Println(time.now ().format ("2006-01-02 15:04:05")) fmt.println (time.now ().format ("Jan")))// month Format("January"))// Month fmt.println (time.now ().format ("Monday"))// week FMT. Println (time. Now (). The Format (" Mon ")) / / weekCopy the code

Exception catching mechanism

PHP supports try like other programming languages… Catch statement, used to catch exceptions in a program, such as:

}catch(Exception $ex){Exception $ex}Copy the code

Go does not have a try… The catch statement, the development suggestion of Go is that programmers return an error when they are developing

Func main() {DSN := "user:pass@tcp(127.0.0.1:3306)/dbname? charset=utf8mb4&parseTime=True&loc=Local" db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err ! = nil {log.fatal (" database connection error ")}Copy the code

If you really must throw an exception to stop the program from executing, you can use panic() and recover to catch it.

func Parse(input string) (s *Syntax, err error) { defer func() { if p := recover(); p ! = nil { err = fmt.Errorf("internal error: %v", p) } }() // ... parser... Panic (" error ")}Copy the code

defer

The original Go language, used for function execution after the release of resources and other subsequent operations

func main() {
	f := GetFile("./1.txt")

	defer f.Close()

	f.Write([]byte("test"))
}

func GetFile(path string) *os.File {

	file, _ := os.Open(path)

	return file
}
Copy the code

concurrent

Go supports concurrency at the language level. Using the Go keyword, you can simply create a Goroutine, or coroutine, which can be understood as a lightweight thread.

func main(){
    go func(){
        fmt.Println("hello world")
    }()
}

Copy the code
  • Coroutines: Start as small as 2KB and can be dynamically adjusted up to 1GB.

  • Thread: the fixed value is 2M.

So Go creates thousands of coroutines on a single machine, supporting high concurrency.

There are two ways of coroutine communication, shared memory and channel

object-oriented

Go is not a traditional object-oriented programming language. It does not support classes or objects, but it can simulate a class through constructs

Type Person struct {name string, Age int, Age struct}Copy the code

Unlike classes, structures do not support inheritance, and it is recommended that Go developers use structure combinations rather than inheritance

type Student struct{
    
    p Person
    
    number string
}
Copy the code
func main() {

	s := Student{
		p: Person{
			name: "test",
			Age:  10,
		},
		number: "123333",
	}

	fmt.Println(s.number)
	fmt.Println(s.p.name)
}
Copy the code

Anonymous embedded

type Student struct {
	Person
	number string
}

func main() {

	s := Student{
		Person: Person{
			name: "test",
			Age:  10,
		},
		number: "123333",
	}

	fmt.Println(s.number)
	fmt.Println(s.name)
}
Copy the code

Structures can also define their own methods like classes


func (s *Student) Say(){
    fmt.Println("My name is:"+s.name)
}

func (s *Student) getName() string{
    return s.name
}

Copy the code

interface

Go, like PHP, supports interfaces, but the difference is that in Go, there is no need to explicitly implement an interface.

  • PHP implements an interface
interface PosterInterface { public function getData(); } class ActivityPosterData implements PosterInterface {public function getData(){// implements PosterInterface}Copy the code
  • Go implements an interface
type Reader interface{ Read(p []byte) (n int, err error) } type File struct{ } func (f *File) Read(p []byte) (n int, err error){ return 10,nil } func main() { var r Reader r = &File{} n, err := r.Read([]byte("test")) if err ! = nil {panic(err)} ftt.println (n)// output: 10}Copy the code

Custom type

Go supports defining new types on top of existing ones

Package main import (" FMT ") type cm int func (c cm) Format() string {return FMT.Sprintf("%d cm ", c) } func (c cm) Read(p []byte) (n int, Err error){return 20,nil} func main() {var r Reader var I cm = 10 fmt.println (i.format ()) 10 cm r = I m, err := r.read ([]byte("cm")) if err! = nil {panic(err)} ftt.println (m) // output: 20}Copy the code

The project management

In PHP, we use Composer to manage project dependencies. Composer is also a community development and is not officially provided by PHP, while Go has provided a very sophisticated project management tool since its inception.

Tool chain

$go build. // Compile $go run main.go // Run $go get github.com/spf13/viper // get third-party packages $go FMT // format $go test // unit test or performance test $go env // Prints environment variables for goCopy the code

Go Module

// Go mod tidy // Go mod downloadCopy the code

style

  • Curly bracket problem

Function, method, if,switch, for, anywhere in Go where big interpolation is used, curly braces cannot stand on a single line

Func b() {} for I := 0; i< 10; i++{ }Copy the code
  • Naming problem
  1. Variable names use luo feng naming
Username
username
Copy the code
  1. It is recommended that the package name be lowercase and the same as the directory name

Differences in Web development

The framework

PHP has large and comprehensive frameworks, such as Yii and Laravel, which have helped us to develop a lot of directly used functions, such as comparison log printing, database ORM operations, queues, Redis reading and so on

In Go, there is a similar framework for Web development, but it is more common to customize the development according to your own needs. For example, I simply develop a Web application, read the database, and then only need to reference the corresponding third-party library.

The library role
github.com/spf13/viper Configuration is read
github.com/spf13/cobra Command line framework
github.com/spf13/pflag Command line arguments
github.com/gin-gonic/gin Web framework
github.com/go-playground/validator Data validation
gorm.io/gorm The ORM database
github.com/robfig/cron Timing task
github.com/sirupsen/logrus The log
go.uber.org/zap The log
github.com/gorilla/websocket websocket
github.com/go-redis/redis Redis

way

The Go language requires only a few lines of code to directly create a Web server that accepts HTTP requests, such as:

package main

import "net/http"

func main() {

	http.HandleFunc("/test", func(rw http.ResponseWriter, r *http.Request) {
		rw.Write([]byte("test"))
	})
	http.ListenAndServe(":8088", nil)
}

Copy the code

PHP alone cannot provide HTTP services without being configured with Nginx or Apache. PHP works as follows:

Recommended directory

If we want to develop our own applications with Go, we recommend the following directory structure, which is widely used by the community, based on which we can reference the third-party libraries we need to customize our own projects.

├ ─ ─ the README. Md ├ ─ ─ API ├ ─ ─ assets ├ ─ ─ build ├ ─ ─ CMD │ ├ ─ ─ apiserver │ │ └ ─ ─ main. Go │ └ ─ ─ apiauth │ └ ─ ─ main. Go ├ ─ ─ │ ├─ deployments │ ├─ docs │ ├─ examples │ ├─ internal │ ├─ Guess │ ├─ Lottery │ ├─ PKG │ PKG ├─ Scripts ├─ Test ├─ Tools ├─ Vendor ├─ web ├─ websiteCopy the code

summary

Compared with PHP, the programs developed by Go language have higher performance and can support a large amount of concurrency. The code of Go language also has a uniform style. Due to the perfect tool chain, it is easier to manage projects. Assemble your own projects using third-party libraries as needed.