当前位置:网站首页>ZUCC_ Principles of compiling language and compilation_ Experiment 01 language analysis and introduction

ZUCC_ Principles of compiling language and compilation_ Experiment 01 language analysis and introduction

2022-06-24 08:30:00 The stars don't want to roll

Compiling language principle and compiling experiment report

Course name Compiling language principle and compiling
Experimental projects Language analysis and introduction

describe

Go( also called Golang) yes Google A kind of development Static strong type 、 A compiled 、 And hairstyles , And Garbage collection Functional programming language .

Go The grammar of is close to C Language , But the declaration of variables is different .Go Support garbage collection function .Go The parallel computing model is based on Tony · Hall's communication sequence process (CSP) Based on , Other languages that take a similar model include Occam and Limbo,Go It also has the characteristics of this model , For example, channel transmission . adopt goroutine Parallel construction with channels can build thread pools and pipes, etc . stay 1.8 Open plug-ins in version (Plugin) Support for , This means that you can now get from Go Dynamic loading part of the function .

And C++ comparison ,Go It does not include enumeration 、 exception handling 、 Inherit 、 Generic 、 Assertion 、 Virtual function and other functions , but Added slice (Slice) type 、 Concurrent 、 The Conduit 、 Garbage collection function 、 Language level support for features such as interfaces .Go 2.0 Version will support generics , For the existence of assertions , They have a negative attitude , At the same time, it also defends that it does not provide type inheritance .

differ Java,Go Native Provides associative arrays ( Also known as hash table (Hashes) Or a dictionary (Dictionaries)).

defects

In publishing Go Language 2.0 Draft of , Officials say there are no generics 、 Exception handling and module for Golang Development is a great hindrance , Equivalent recognition Golang Not having these features is a design error .

The development history

2007 year ,Google Design Go, The purpose is to improve the performance in multi-core 、 Network machine (networked machines)、 Large code base (codebases) Development efficiency in the case of . At that time in Google, Designers want to address the shortcomings of other languages , But still retain their advantages .

  • Static types and runtime efficiency .( Such as :C++)

  • Readability and ease of use .( Such as :Python and JavaScript)

  • High performance network and multi process .

Designers are mainly influenced by the “ Don't look like C++” inspire .

Go On 2009 year 11 Officially announced in June , edition 1.0 stay 2012 year 3 Published in . after ,Go Widely used in Google As well as many other organizations and open source projects .

stay 2016 year 11 month ,Go( A sans serif body ) and Go Mono typeface ( An equal width font ) By designer Charles · Bigelow and Chris · Holmes released . Both fonts use WGL4, And according to DIN 1450 standard , Can be used clearly large x-height and letterforms .

stay 2018 year 8 month , The local icon has been changed . However ,Gopher mascot Still have the same name .

stay 2018 year 8 month ,Go Major contributors to the release of two new features of the language “ Draft design —— Generics and exception handling , At the same time seek Go User feedback .Go Because in 1.x when , Lack of support for generic programming and lengthy exception handling have been criticized .

Language features

Programming paradigm

image-20220620174108148

go Is the classic functional programming 、 Static strong type 、 A compiled 、 And hairstyles , And has the garbage collection function programming language , It shows the code extension ability of functional programming , And the mutual and random assembling of functions .

features

  • stateless: Function does not maintain any state . The core spirit of functional programming is stateless, In short, it cannot exist , You give me the data and I'll throw it out after processing , The data inside is constant .
  • immutable: The input data cannot be moved , It is dangerous to input data , So return a new data set .

advantage

  • No state, no harm .
  • Parallel execution does no harm .
  • Copy-Paste Refactoring code does no harm .
  • There is no sequential problem with the execution of functions .

Because there's no state , So the code doesn't need locks at all in parallel ( Locks that do not require state modification ), So you can desperately concurrence , On the contrary, it can make the performance very good

go Unique features of language

  1. Go Language opposes function and operator overloading (overload)
  2. Go Language support classes 、 Class member method 、 Class , But against inheritance , Against virtual functions (virtual function) And virtual function overloading .
  3. Go The language also abandons constructors (constructor) And destructors (destructor)
  4. In giving up a lot of OOP After characteristic ,Go Language is a great gift : Interface (interface) .

Writing style

Go There are defined writing styles as follows

  1. You don't need to write semicolons at the end of each line (;).
  2. Curly braces ({) Can't wrap .
  3. if Judgmental and for The loop doesn't need to be wrapped in parentheses .
  4. Use tab Do typesetting

Apart from the second point ( Newline will cause compilation errors ), In case of non-compliance with the above provisions , You can still compile , But it uses built-in gofmt After the tool , Will automatically clean up the code , Make it conform to the prescribed writing style .

package main

import "fmt"

func main() {
    
	fmt.Println("Hello, World")
}

image-20220302083213420

Project framework

Go The workspace for is located in GOPATH, Its directory structure is as follows :

Catalog purpose
src Referenced external library
pkg Compile time , Generated object file
bin Compiled program

Light synergy

Go The main feature of is the easy-to-use concurrent design , be called Goroutine, through Goroutine It can make the program execute asynchronously , You don't have to worry about a function that breaks the program , therefore Go It is also very suitable for network services .

package main

import (
	"io"
	"net/http"
)

func hello(w http.ResponseWriter, r *http.Request) {
    
	io.WriteString(w, "Hello world!")
}

func main() {
    
	http.HandleFunc("/", hello)
	http.ListenAndServe(":8000", nil)
}

image-20220302083518458

Goroutine Is a thread like concept , It belongs to fiber path ( It is different from CO process and thread ). Threads belong to the system level , Generally speaking, creating a new thread consumes more resources and is difficult to manage ; The main function of a coroutine is to provide concurrency within a thread , You can't use multiple processor threads . and Goroutine Like a lightweight thread , One Go The program can execute more than tens of thousands Goroutine, And these features are native , It can be closed at any time 、 end , And run on multiple processor threads . One core can have multiple Goroutine, through GOMAXPROCS Parameters you can limit Gorotuine You can use several system threads to avoid losing control .

It can also be seen from time to time in the built-in official package Goroutine Application , Like net/http The function used to listen for network services in is actually to create a loop that executes continuously Goroutine; At the same time epoll etc. IO Multiplexing mechanism maintenance Goroutine The event loop of .

data type

type describe
Boolean type Boolean values can only be constants true perhaps false. A simple example :var b bool = true
Numeric type integer int And floating point float32、float64,Go The language supports integer and floating-point numbers , And support plural , The operation of the middle bit adopts complement
String type A string is a sequence of characters connected by a fixed length of characters .Go A string of strings is concatenated by a single byte .Go Language string byte use UTF-8 Code identification Unicode Text
Derived type Pointer types (Pointer)、 An array type 、 Structured type (struct)、Channel type 、 Function type 、 Slice type 、 Interface type (interface)、Map type
package main

import "fmt"

func main() {
    
	var a = uint(12345678)
	fmt.Println(a)
	var b = int(-12345678)
	fmt.Println(b)
	var c = float64(123.123)
	fmt.Println(c)
	var d = complex128(-123 + 123i)
	fmt.Println(d)
	var e = byte(123)
	fmt.Println(e)
	var f = rune(-123123)
	fmt.Println(f)
	var g = uintptr(123)
	fmt.Println(g)
}

image-20220302085548907

Conversion type

go Implicit conversion of type... Is not supported , such as :

package main
import "fmt"

func main() {
      
    var a int64 = 3
    var b int32
    b = a
    fmt.Printf("b  by  : %d", b)
}

This program reports an error and cannot be compiled , But if it changes to b = int32(a) It won't be wrong :

image-20220302091041984

Array

An array is a sequence of numbered, fixed length data items of the same unique type , This type can be any primitive type, such as integer 、 String or custom type .

package main

import "fmt"

func main() {
    
	var n [10]int /* n  Is a length of  10  Array of  */
	var i, j int

	/*  Is an array  n  Initialization element  */
	for i = 0; i < 10; i++ {
    
		n[i] = i + 100 /*  Set the element to  i + 100 */
	}

	/*  Output the value of each array element  */
	for j = 0; j < 10; j++ {
    
		fmt.Printf("Element[%d] = %d\n", j, n[j])
	}
}

image-20220302085811192

The pointer

We all know , Variable is a convenient placeholder , Used to refer to the memory address of the computer .Go The address of a language is &, Put a variable before use, it will return the memory address of the corresponding variable .

package main

import "fmt"

func main() {
    
	var a int= 20   /*  Declare the actual variable  */
	var ip *int        /*  Declare pointer variables  */

	ip = &a  /*  Storage address of pointer variable  */

	fmt.Printf("a  The address of the variable is : %x\n", &a  )

	/*  Storage address of pointer variable  */
	fmt.Printf("ip  Pointer address of variable storage : %x\n", ip )

	/*  Use pointers to access values  */
	fmt.Printf("*ip  The value of the variable : %d\n", *ip )
}

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-15Hm14Cy-1655718082655)(http://owem-pictures.oss-cn-hangzhou.aliyuncs.com/img/image-20220302085947428.png)]

Structure

Arrays can store the same type of data , But in the structure, we can define different data types for different items . A struct is a data set consisting of a series of data of the same or different types .

package main

import "fmt"

type Books struct {
    
	title   string
	author  string
	subject string
	book_id int
}

func main() {
    
	var Book1 Books /*  Statement  Book1  by  Books  type  */
	var Book2 Books /*  Statement  Book2  by  Books  type  */

	/* book 1  describe  */
	Book1.title = "123"
	Book1.author = "456"
	Book1.subject = "789"
	Book1.book_id = 10

	/* book 2  describe  */
	Book2.title = "321"
	Book2.author = "654"
	Book2.subject = "987"
	Book2.book_id = 100

	/*  Print  Book1  Information  */
	printBook(&Book1)

	/*  Print  Book2  Information  */
	printBook(&Book2)
}
func printBook(book *Books) {
    
	fmt.Printf("Book title : %s\n", book.title)
	fmt.Printf("Book author : %s\n", book.author)
	fmt.Printf("Book subject : %s\n", book.subject)
	fmt.Printf("Book book_id : %d\n", book.book_id)
}

image-20220302090320131

section

Slicing is an abstraction of arrays . The length of the array cannot be changed , In a particular scenario, such a collection is not applicable ,Go Provides a kind of flexibility , Powerful built-in type slicing (“ The dynamic array ”), Compared with array, the length of slice is not fixed , You can append elements , In addition, it may increase the volume of slices .

package main

import "fmt"

func main() {
    
   var numbers = make([]int,3,5)

   printSlice(numbers)
}

func printSlice(x []int){
    
   fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x)
}

image-20220302090420716

MAP

Map Is an unordered set of key value pairs .Map The most important point is through key To quickly retrieve data ,key Similar to index , The value that points to the data .Map It's a collection , So we can iterate it like we iterate arrays and slices . however ,Map Is chaotic , We can't decide the return order , This is because Map It's using hash Table to achieve .

package main

import "fmt"

func main() {
    
    var countryCapitalMap map[string]string /* Create set  */
    countryCapitalMap = make(map[string]string)

    /* map Insert key - value Yes , The corresponding capital of each country  */
    countryCapitalMap [ "France" ] = " In Paris, "
    countryCapitalMap [ "Italy" ] = " The Roman "
    countryCapitalMap [ "Japan" ] = " Tokyo "
    countryCapitalMap [ "India " ] = " New Delhi "

    /* Use the key to output map values  */
    for country := range countryCapitalMap {
    
        fmt.Println(country, " The capital is ", countryCapitalMap [country])
    }

    /* See if the element exists in the collection  */
    capital, ok := countryCapitalMap [ "American" ] /* If it's true , There is , Otherwise, it doesn't exist  */
    /*fmt.Println(capital) */
    /*fmt.Println(ok) */
    if (ok) {
    
        fmt.Println("American  Its capital is ", capital)
    } else {
    
        fmt.Println("American  There is no capital of ")
    }
}

image-20220302090745281

Interface

Go The language provides another data type, the interface , It defines all the common methods together , Any other type that implements these methods implements this interface .

package main

import (
    "fmt"
)

type Phone interface {
    
    call()
}

type NokiaPhone struct {
    
}

func (nokiaPhone NokiaPhone) call() {
    
    fmt.Println("I am Nokia, I can call you!")
}

type IPhone struct {
    
}

func (iPhone IPhone) call() {
    
    fmt.Println("I am iPhone, I can call you!")
}

func main() {
    
    var phone Phone

    phone = new(NokiaPhone)
    phone.call()

    phone = new(IPhone)
    phone.call()
}

image-20220302091159919

Error handling

Go The language provides a very simple error handling mechanism through a built-in error interface .

f, err := os.Open(filename)
if err != nil {
    
	log.Println("Open file failed:", err)
	return
}
defer f.Close()
... //  Operation has been opened f file 

defer keyword

The first is defer keyword . defer Statement means whether or not an exception occurs in the program , Automatically execute relevant code when the function exits

The function allows multiple return values

The last return value of most functions will be error type , error Type is just a system built-in interface

type error interface {
    
Error() string
}
package main

import (
    "fmt"
)

//  Define a  DivideError  structure 
type DivideError struct {
    
    dividee int
    divider int
}

//  Realization  `error`  Interface 
func (de *DivideError) Error() string {
    
    strFormat := ` Cannot proceed, the divider is zero. dividee: %d divider: 0 `
    return fmt.Sprintf(strFormat, de.dividee)
}

//  Definition  `int`  A function of type division 
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() {
    

    //  Normal condition 
    if result, errorMsg := Divide(100, 10); errorMsg == "" {
    
            fmt.Println("100/10 = ", result)
    }
    //  When the divisor is zero, an error message is returned 
    if _, errorMsg := Divide(100, 0); errorMsg != "" {
    
            fmt.Println("errorMsg is: ", errorMsg)
    }

}

image-20220302091304518

Concurrent

Go Languages support concurrency , We just need to pass go Keyword to open goroutine that will do .goroutine It's a lightweight thread ,goroutine The dispatch of is made by Golang Managed at run time .

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() {
    
	go say("world")
	say("hello")
}

image-20220302091527534

passageway

passageway (channel) Is a data structure used to transfer data . Channels can be used for two goroutine By passing a value of the specified type to synchronize operation and communication between . The operator <- Used to specify the direction of the channel , To send or receive . If no direction is specified , It's a two-way channel .

package main

import "fmt"

func sum(s []int, c chan int) {
    
        sum := 0
        for _, v := range s {
    
                sum += v
        }
        c <- sum //  hold  sum  Send to channel  c
}

func main() {
    
        s := []int{
    7, 2, 8, -9, 4, 0}

        c := make(chan int)
        go sum(s[:len(s)/2], c)
        go sum(s[len(s)/2:], c)
        x, y := <-c, <-c //  From the tunnel  c  In the receiving 

        fmt.Println(x, y, x+y)
}

image-20220302091714696

Application field

Go Language is mainly used in the following fields :

1. Server programming , It mainly includes processing logs 、 Data packaging 、 Virtual machine processing 、 File system, etc ;
  1. Distributed systems 、 Database agent, etc ;
  1. Network programming , Include Web application 、API application 、 Download apps, etc ;
  1. database , It can realize the component implementation of the database ;
  1. Cloud platform , At present, many foreign cloud platforms are adopting Go Development .

原网站

版权声明
本文为[The stars don't want to roll]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240605219069.html