Basic types and function usage of go

Posted by installer69 on Sun, 02 Jan 2022 18:04:30 +0100

Basic types and function usage of go

1, go language introduction

1 go language introduction

Go, or Golang, is a programming language officially disclosed by Google in November 2009. It is characterized by simple syntax and fast speed.

Go is a static (compiled) strongly typed language and a weakly typed language different from analytical languages (static: fixed type, strong type: direct operation is not allowed for different types).

python dynamic strongly typed language.

Compiled languages: Java, C, C + +, c#, go

Explanatory language: python, js, php

Compiled language involves cross platform issues because it needs to be compiled into the executable file of the platform. For example, java runs on the jvm. go language can perform cross platform compilation, that is, cross compilation. For example, compile from windows to an executable file on linux.

Interpretability does not involve cross platform issues, because each platform has its own interpreter.

2 go language features

  • Cross platform compiled language, cross compilation
  • channel, slice, and route
  • There is a garbage collection mechanism
  • Support object-oriented and process oriented programming patterns (go has no concept of class in object-oriented, python is completely object-oriented)

3. Historical development of go

  • November 7, 2009 weekly 2009-11-06 - earlier version
  • August 19, 2015 go1 5 - architecture changes implemented while maintaining compatibility with the old version. The "last remaining C code" is removed in this update. (from then on, lift yourself up and write yourself)
  • August 24, 2018 go 1.11: added modules, package management
  • August 2020 go 1.15

4. Application fields of go language

Google, Facebook, Tencent, qiniuyun

go language writing: docker, k8s, blue whale

Application fields: service development, concurrency, distribution, micro service, etc.

2, go language development environment

1 go environment configuration

  1. IDE (Golan): integrated development environment.
  2. Development environment: sdk [take the next step along the way]
  3. The go language does not need to be manually added to environment variables (python, java)
  4. go version: print the version information of go

matters needing attention:

  1. goland create project: you need to select the installation path of go sdk [selected by default].

  2. Specify gopath: the code must be placed under this path, otherwise it cannot be executed. [gopath will be created in the environment variable by default, which needs to be manually customized and modified]. Meanwhile, all go codes must be placed in the src folder under this path, otherwise [E:\Go_project\src \ project name] cannot be executed.

  3. The path and file should not appear in Chinese.

2 go common commands

go version  // View the version information of go
go env  // View environment variables for go
  - GO111MODULE=on  // Go. Is used Mod mode
  - GOPATH=E:\Go_project  // Code storage path
  - GOROOT=D:\golang  // go sdk installation path
  - ...

go build  // compile. Compiled languages need to be compiled before execution, and compiled into executable files
go run  // Compile and execute. Two steps and one step
go clean  // Clear compiled executable

go fmt  // Format code [useless]
go get  // Downloading and installing packages and dependencies is equivalent to pip install

3, The first hello world

//Single-Line Comments 
/*multiline comment */

Compiled language: 
  - compile: go build .\test01.go
  - implement: .\test01.exe
- Compile and execute: go run .\test01.go
package main  // Declare the package name, which is main

import "fmt"  // Built in package

// A main function is defined, which is the entry to run the go project [so a compiled language must have an entry]
func main() {
	fmt.Println("hello world")  // Equivalent to print in python (print in Python is a built-in function)

Note: each go file must have a package name to represent that it belongs to a package.

There are several ways to execute files in Golan, such as file and package. [it can be configured by yourself. Generally, package can be used in a project, and file can be used for testing]

Four variables

1 variable definition

  • var variable name variable type = variable value

    var age int = 10

    go variables must be used if they are defined. If they are not applicable, an error will be reported.

  • var variable name = variable value type derivation (can not write type)

    var age = 10

    package main
    import "fmt" // Built in package
    func main() {
    	var age int = 10
    	var name string = "YangYi"
    	fmt.Printf("%T\n", age)  // int (look at the type, there is no type method in python, there is no automatic line feed, and it needs to be manually \ n)
    	fmt.Printf("%T\n", name)  // string
    	fmt.Print()  // Print without line breaks
    	fmt.Println()  // Print wrap
    	fmt.Printf("%T\n", name)  // View type
    	fmt.Printf("%p", &name)  // 0xc0000881e0

    Once the variable type in go is defined, it cannot be changed later. (compiled languages are common, and can be modified in python. The memory address stored in python can be changed, so the type can be changed)

  • Variable name: = brief declaration of variable value (type and var keyword are not written)

    a := 10

    a := 10
    var a int = 100
    var a = 99  // Repeated definition and error (variables cannot be defined repeatedly, and variables must be defined before use)
    /* Definition only, no assignment */
    var a int  // Yes (only in this way)
    var a  // No (because there is no type, I don't know what a is, because the type needs to be determined in the definition stage and can't be changed)
/* Declare multiple variables */
var width, height int = 100, 50  // First kind
var width, height = 100, 50  // Second
width, height := 100, 50  // Third

var (
    name   = "YangYi"  // No type
    age  int  = 29  // Assignment type
    height int  // statement
/* Small pit */
var a int =10
var b =99
b,a:=99,100    //This does not report an error. We think it is a duplicate definition. As long as there is an undefined variable on the left side of the colon, you can

2 variable definition specification

2.1 variable naming specification

Hump is recommended for variable commands (case has special meaning [meaning of private and public]);
It is recommended to underline the go file name; (ps: underscores are recommended in python; humps are recommended in java; humps are recommended for variable names in js)

A name must start with a letter (Unicode letter) or underscore, followed by any number of letters, numbers or underscores;

Uppercase letters and lowercase letters are different: name and name are two different variables;

Keywords and reserved words are not recommended as variable names;

2.2 keywords in go language

// There are 25 keywords in Go language
break      default       func     interface   select
case       defer         go       map         struct
chan       else          goto     package     switch
const      fallthrough   if       range       type
continue   for           import   return      var

// There are 37 reserved words in Go language, mainly corresponding to built-in constants, types and functions
 Built-in Constants : true false iota nil
 Built in type:  int int8 int16 int32 int64
          uint uint8 uint16 uint32 uint64 uintptr
          float32 float64 complex128 complex64
          bool byte rune string error
 Built in function: make len cap new append copy close delete
          complex real imag
          panic recover

Five data types

1. Basic data type

  • number

    // Signed shaping
    int On 32-bit machines int32,On 64 bit machines int64
    int8 Indicates that the integer range is: 8 bits, 8 bits bit Yes 1 byte ,Negative numbers and the 7th power of 0,2-1 Scope of
    int16 2 Minus one to the 15th power of
    Examples of strong types:
    var a int8 = 10
    var b int16 = 20
    fmt.Println(a + b)  // Error report [go is a strong type, and there is no automatic type conversion in java]
    fmt.Println(int16(a) + b)
    byte: It's an int8 package
    rune: It's an int32 package
    var a byte = 99  // int8
    var b byte = 'b'  // It stores characters, which are also numbers
    fmt.Println(b)  // 98
    var c rune = 'you'  // It can be printed. The characters are actually numbers
    fmt.Println(c)  // 20320
    var d byte = 'you'  
    fmt.Println(d)  // Error reported, out of range
    // Unsigned shaping
    uint8  2 Minus one to the power of eight (Define a person's age)
    // Floating point number (decimal), indicating the number of digits after the decimal point
    // complex
    var a complex64 = 20 + 10i
  • character string

    "Double quotation mark wrapping"
    `Backquote wrapping`  // Same as js; Is' 'in python
  • Boolean type

    bool true and false
    var flag bool = false
    var flag = true

Default value of data type: numeric type is 0, string type is empty string, and boolean type is false.

java go
byte int8
short int16
int int32
long int64
float float32
double float64

2 constant

const keyword is used for constant definition in go; The constant in java is the final keyword; Uppercase in python.

  • const variable name variable type = variable value

    const name string = "yangyi"  // Constants can be defined and not used, and no error will be reported
  • const variable name = variable value

    const age = 90
  • Other definition methods

    const name, age = "yangyi", 18
    const (
    	name string = "yangyi"
        age = 18
    // I don't think I can use it
    const (
    	s1 = iota
        s3 = iota
        s4 = 99
    fmt.Println(s1)  // 0
    fmt.Println(s2)  // 1
    fmt.Println(s3)  // 2
    fmt.Println(s4)  // 99
    fmt.Println(s5)  // 99. That's strange
    const (
    	s1 = iota
        s3 = iota
        s4 = 99
        s5 = iota
    fmt.Println(s1)  // 0
    fmt.Println(s2)  // 1
    fmt.Println(s3)  // 2
    fmt.Println(s4)  // 99
    fmt.Println(s5)  // 4 too strange

Six functions

1 basis of function

func Function name(Parameter name type, Parameter name type)(return type, return type){
    Function body content
    return Return value 1, Return value 2

Function usage example

// 1. No return value for parameters
func add(a int, b int){
    fmt.Println(a + b)

add(100, 200)  // Call function  

// 2. There are parameters without return value, and there are multiple parameters of the same type
func add(a, b int){
    fmt.Println(a + b)

// 3. There are parameters without return value, and there are multiple parameters of different types
func add(a, b int, msg,name string){

// 4 multiple parameters, one return value
func add(a, b int) int {
    return a + b

// 5 multiple parameters and multiple return values [python and go support multiple return values]
func add (a, b int) (int, int){
    return a + b, a * b

a, b := add(100, 200)  // Multiple return values need to be accepted with multiple variables [the same as python]
a, _ := add(3, 4)  // The underline in python can be printed, but it is empty in go

// 6 command return value
func add(a, b int) (c int, d int){
    c = a + b  // That is, the variables of C and d have been declared in the function body
    d = a * b  
    return  // It will directly return c,d without writing return c,d

2 function advanced

Functions are first-class citizens and can be assigned to variables [the same is true in python]

In compiled languages, unlike interpretative languages, functions are not defined first and then used. They can be found after compilation.

// Anonymous function (defined inside the function and cannot have a name): lamdba in python
// First kind
func (){  
}()  // Anonymous function direct call

// Second
var a func()  // Define a variable of type func() [HA HA]
a = func(){  // At this time, a is a function    
    fmt.Println("I'm an anonymous function")
a()  // I'm an anonymous function
// 7. The return value of the function is
func test() func(){
    return func(){
        fmt.Println("I'm a function that returns...")
a := test()
fmt.Println(a)  // 0x5451e0 [ print function name, get the memory address of the function ]

// 8 return value function with parameters
// The return value type must match the returned function type, that is, func() and func(msg string) are not the same type
func test() func(msg string){  // The return value type must match the returned function type
    return func(msg string){
        fmt.Println("I'm a function that returns...")

a := test()
a("hello")  // function call

// 9. The return value of the function is a function with parameters and return value
func test() func(a, b int) int {
    return func(a, b int) int {
        return a + b

a := test()  // The type of a is var a func (a, B, int) int
fmt.Println(a(2, 3))

// 10. The function parameter is the function type, and the return value is the function type with parameter and return value
func test(f func()) func(a, b int) (int, int){
    f()  // f function execution
    return func(a, b int) (int, int){
        f()  // f function execution
        return a + b, a * b

// Function operation
a, b := test(
        fmt.Println("I am a function parameter...")
)(3, 4)  // function call

// perhaps 
f := func(){
    fmt.Println("I am a function parameter...")
f1 := test(f)
a, b := f1(3, 4)
fmt.Println(a, b)

3 closure function

① Defined inside the function; ② Reference to external scope;

A closure function is actually a way to pass parameters to a function.

func test(age int) func() {
    // age := 18  
    a := func(){  // Defined inside a function
        fmt.Println(age)  // Reference to external scope
    return a 

a := test(19)
a()  // Call of closure function [no parameters are passed in, but actually parameters are passed in]

// Generally speaking, after the function is executed, the parameters should be released. However, due to the existence of closure function, age has not been released, and something has a reference to it. [lead out memory escape: normally, it should be recycled, but it is not recycled]

// Decorator is a typical application of closure function (there is no syntax sugar of decorator in go language, but there is syntax sugar in python)

4 type rename

type MyFunc func()  // Type rename
func test() MyFunc  {
    return func(){

type MyFunc func(a,b int)(int,string)
func test() MyFunc  {
	return func(a,b int)(int,string) {
		return 10,"ok"

type Myint int  // Here Myint and int are not the same type of bronze drum
var a int = 10
var b Myint = 100
fmt.Println(a + b)  // report errors
fmt.Println(a + int(b))  // Cast type

5 scope of variable

Under the same package, the function name cannot be the same. For example, they are all in the main package

// The first way
var a int   //Global variables are globally valid. As long as they are changed, they are changed
func main() {
	fmt.Println(a)  //0
	fmt.Println(a) //19
	test1()  //99
	fmt.Println(a) //99

func test1()  {
	fmt.Println(a)  // 99

// The second method is [local - > Global - > built-in]
var a int   //Global variables are globally valid. As long as they are changed, they are changed
func main() {
	var a int
	fmt.Println(a)  //0
	fmt.Println(a) //19
	test1()  // 0
	fmt.Println(a) //19

func test1()  {

Topics: Go