GO -- define variables, constants, enumerations


Domestic download address: https://studygolang.com/dl

1, GO code considerations

  • When we write code, there will be a package declaration at the beginning of the. go file, which package the file belongs to. Package < package name >
  • If the package name declared by package is the main package, the code will eventually be compiled into an executable file. If the declared package is the package of other tool classes, it will not be compiled into executable files
  • To be compiled and executed in the main package, you must define the fun main() {} function, which is the entry function of the program. The main function has no parameters and no return value.
  • Outside the function of go code, only the declaration of identifier (variable \ constant \ function \ type \) can be placed

2, Go language variables

1. Define variables

1.1 define variables with var keyword: var variable name type (variables defined in go will have an initial value, such as 0 or null value)

package main

import "fmt"

// Define variables
func variablezerovale(){
	var a int                     // Defining integer variables
	var b string                  // Define string type variables
	fmt.Printf("%d %q\n", a, b)   // Variables defined in go will have an initial value (such as 0 or null value). Here, the printf method is used to print quoted strings using%q
}


func main() {
	variablezerovale()
}

give the result as follows

E:\GoProject\src\gitee.com\LTP\day01\helloWorld>go run edu.go
0 ''

1.2 define variables and assign values (multiple variables can be assigned values)

package main

import "fmt"

func variable(){
	var a, c  int = 3, 4                  // You can assign values to multiple variables (Note: the variables declared in go must be used in the code, otherwise an error will be reported)
	var b string = "abc"                  
	fmt.Println(a, b, c)                  // Note: the variables declared in go must be used in the code, otherwise an error will be reported
}

func main() {
	variable()
}

The results are as follows

E:\GoProject\src\gitee.com\LTP\day01\helloWorld>go run edu.go
3 abc 4

1.3 when defining variables, the variable type can be omitted (it will be judged automatically)

package main

import "fmt"

func variabletypeDeduction() {
	// Omit the defined variable types, such as int, string...
	var a, b, c = 3, "bbb", false // When we do not specify variable types, multiple types of variables can be written together
	var d = true
	fmt.Println(a, b, c, d)
}

func main() {
	variabletypeDeduction()
}

results of enforcement

E:\GoProject\src\gitee.com\LTP\day01\helloWorld>go run edu.go
3 bbb false true

1.4 the simpler writing method (using the method of: =, which is the same as the var keyword method) is more commonly used

package main

import "fmt"

func variableshort() {
	// Omit the var keyword and define variables with colon ':'
	a, b, c := 3, "bbb", false
	c = true // Note: when this variable has been defined and the value is modified later, you can directly use the variable name = value, and you can't use: to define the variable (if c:=1, you can't use c:=2 later, and you can use c=2 directly)
	fmt.Println(a, b, c)
}

func main() {
	variableshort()
}

results of enforcement

E:\GoProject\src\gitee.com\LTP\day01\helloWorld>go run edu.go
3 bbb true

1.5 variables can also be defined outside the function

  • Note: when defining variables outside the function, the var keyword must be used, and the definition method remains unchanged (variables cannot be defined outside the function by: =)
  • For variables defined outside the function, the scope is valid within the package (package declared), not a global variable.
  • When using var to define variables, you can use the var() method to define variables in parentheses
    Example:
package main

import "fmt"

// Directly defined with var keyword
var aa = 666
var bb = "xxx"

// It is defined by var()
var (
	a = 123
	b = true
	c = "abc"
)

func main() {
	fmt.Println(aa, bb, a, b, c)
}

results of enforcement

E:\GoProject\src\gitee.com\LTP\day01\helloWorld>go run edu.go
666 xxx 123 true abc

2. Understand Go built-in variable types

  • bool, string: Boolean and string types
  • (u)int, (u)int8, (u)int16, (u)int32, (u)int64: integer type (if u is added before it, there will be signed integer type). For example, (u)int8, (u)int16, (u)int32, (u)int64 is an integer type with a specified length. By default, the length is determined according to the operating system. In a 64 bit system, its length is 64 bits;
  • uintptr: pointer. The length of the pointer is also determined according to the operating system
  • Byte: byte, 8-bit byte
  • Rune: the character type of go language, similar to char type. The length of rune is 32 bits
  • float32, float64: float type
  • complex64, complex128: complex type (involving real part and imaginary part). The length of real part and imaginary part is 64 or 128

2.1 complex complex type

  • Recall the plural in the higher number

    • Imaginary number of complex number: i = √ - 1 (i = radical - 1)
    • So I ² = - 1,i ³ = - i . . . .
    • Complex number: 3 + 4i (in this formula, 3 is the real part and 4i is the imaginary part)
  • When the imaginary number i appears as a power, there are several equations

  • Euler formula

2.1.1 verify plural numbers in Go language
package main

import (
	"fmt"
	"math/cmplx"
)

func euler() {
	a := 3 + 4i               // Define a complex number (Note: 4i here is the imaginary part of the complex number, not 4*i, so it cannot be written as 4*i)
	fmt.Println(cmplx.Abs(a)) // cmplx.Abs(a) represents the module of complex a, i.e. | a|
}

func main() {
	euler()
}

Output result: 3 + 4i = 5

E:\GoProject\src\gitee.com\LTP\day01\helloWorld> go run .\edu.go
5
2.1.2 verify Euler formula with Go language
  • The complex number of complex64 is composed of the real part of float32 and the imaginary part of float32, respectively
  • The complex number of complex128 is composed of the real part of float64 and the imaginary part of float64, respectively
package main

import (
	"fmt"
	"math"
	"math/cmplx"
)

func euler() {
	fmt.Println(cmplx.Pow(math.E, 1i*math.Pi) + 1) // Here, the imaginary number i is represented by 1i. If i is written directly, it will be mistaken for a variable
	// The first parameter in cmplx.Pow() is the base e, followed by 1i * math.Pi (i.e. I * π) to the power of E. This whole paragraph is actually Euler's formula
	// The real result of this formula should be 0, but since the real part and imaginary part of the complex number here are calculated by the standard of floating point numbers, floating point numbers are very incorrect in the programming language, so the value obtained is a non-zero value infinitely close to 0
}

func main() {
	euler()
}

Output results

E:\GoProject\src\gitee.com\LTP\day01\helloWorld> go run .\edu.go
(0+1.2246467991473515e-16i)

  • In the complex type, e is the base. In addition to math.E in cmplx.Pow(), e can also be directly represented by cmplx.Exp()
package main

import (
	"fmt"
	"math"
	"math/cmplx"
)

func euler() {
	fmt.Println(cmplx.Pow(math.E, 1i*math.Pi) + 1) // Here, the imaginary number i is represented by 1i. If i is written directly, it will be mistaken for a variable
	// The first parameter in cmplx.Pow() is the base e, followed by 1i * math.Pi (i.e. I * π) to the power of E. This whole paragraph is actually Euler's formula
	// The real result of this formula should be 0, but since the real part and imaginary part of the complex number here are calculated by the standard of floating point numbers, floating point numbers are very incorrect in the programming language, so the value obtained is a non-zero value infinitely close to 0

	fmt.Println(cmplx.Exp(1i*math.Pi) + 1) // cmplx.Exp() directly takes e as the base and fills in the power of E in ()
}

func main() {
	euler()
}

Check the results, and the two output results are consistent

E:\GoProject\src\gitee.com\LTP\day01\helloWorld> go run .\edu.go
(0+1.2246467991473515e-16i)
(0+1.2246467991473515e-16i)

  • Use printf to trade off the result of Euler formula in Go language (for example, take three decimal places), and you can get the result 0
package main

import (
	"fmt"
	"math"
	"math/cmplx"
)

func euler() {
    // The method of Printf("%.3f") retains three decimal places
	fmt.Printf("%.3f", cmplx.Exp(1i*math.Pi)+1) // cmplx.Exp() directly takes e as the base and fills in the power of E in ()
}

func main() {
	euler()
}

Output results

E:\GoProject\src\gitee.com\LTP\day01\helloWorld> go run .\edu.go
(0.000+0.000i)

3. Cast to Go

  • Type conversion is mandatory (Go only has mandatory type conversion and no implicit type conversion). Data types are not automatically converted. What type of data is defined is what type is passed in

Example: define three int type variables a,b,c, where a=3,b=4, c = √ (a) ²+ b ²) , Here, the math.Sqrt() method is used to open the root, and the printed value of c should be 5

  • However, if c = math.Sqrt(a*a + b*b) is written in this way, an error will be directly reported in red. The reason is that the parameters passed in by math.Sqrt() must be the data type of float64, while a and B are int types, which cannot be passed in directly and need to be converted( The following figure shows the source code of the math.Sqrt() method

    Correct code
package main

import (
	"fmt"
	"math"
)

func triangle() {
	var a, b int = 3, 4
	var c int
	c = int(math.Sqrt(float64(a*a + b*b))) // You need to convert (a*a + b*b) to float64 type first because the math.Sqrt() method only receives data of float64 type
	                                       // Then convert the value of the open radical into int type and pass it to variable c. because c has been defined as int type, the passed in must also be int type
	fmt.Println(c)
}
func main() {
	triangle()
}

The output is 5

E:\GoProject\src\gitee.com\LTP\day01\helloWorld> go run .\edu.go
5

3, Constants for Go language

1. Definition of constants

  • When a constant does not define a type, similar to text substitution, the value of the constant can be used as various types
  • When defining types, you must follow cast
  • Constants are defined by using the keyword const. The definition method is similar to var. they can be defined outside the function to make them effective in the package, or they can be defined in batch by const()
  • In go language, the naming of constants does not need to be capitalized like the specifications of other languages. In go language, capitalization has special meaning. Therefore, when defining constants, the naming method is the same as that of variables
    Example:
package main

import (
	"fmt"
	"math"
)

func consts() {
	const filename string = "abc.txt" // const keyword defines a constant, followed by a type
	const dir = "root/"               // As with variables, types can be omitted
	const a, b = 3, 4                 // In constants, when we do not define types, for example, a and b can be used as 3 and 4 of int type, string, float, etc.
	var c int

	// Therefore, when constants A and B are introduced here, there is no need for type conversion
	c = int(math.Sqrt(a*a + b*b))
	fmt.Print(c)
}
func main() {
	consts()
}

The output result is "abc.txt 5"

2. Special constants (enumeration types)

2.1 Go provides iota parameter to define enumeration type data

Example: the normal enumeration types are as follows: a variable has a value, and the value is incremented

package main

import (
	"fmt"
)

func enums() {
	// Ordinary enumeration types are also defined with const constants
	const (
		a = 0
		b = 1
		c = 2
	)
	fmt.Println(a, b, c)
}
func main() {
	enums()
}

The output result is "0,1,2"

  • Go defines the enumeration type
package main

import (
	"fmt"
)

func enums() {
	const (
		a = iota    // The Go language defines enumeration. You only need to assign the iota element to the first constant, and the subsequent constants will be incrementally assigned from 0
		b
		c
	)
	fmt.Println(a, b, c)
}
func main() {
	enums()
}

The output result is "0,1,2"

2.2. If the iota element is referenced, you can use "" To skip an incremental enumeration

Example:

package main

import (
	"fmt"
)

func enums() {	
	const (
		a = iota
		_          // Use_ Instead of receiving this enumeration value
		b
		c
	)
	fmt.Println(a, b, c)
}
func main() {
	enums()
}

The output result is "0,2,3"( Enumerating number 1 was skipped by '' (received)

2.3 advanced usage of iota

  • Official introduction: in Go, iota is recommended for the creation of enumeration constants. Since iota can be used as part of an expression and can be implicitly repeated, it is easy to build complex value sets.

The official use cases are as follows:

type ByteSize float64

const (
    _           = iota // ignore first value by assigning to blank identifier
    KB ByteSize = 1 << (10 * iota)
    MB
    GB
    TB
    PB
    EB
    ZB
    YB
)

func (b ByteSize) String() string {
    switch {
    case b >= YB:
        return fmt.Sprintf("%.2fYB", b/YB)
    case b >= ZB:
        return fmt.Sprintf("%.2fZB", b/ZB)
    case b >= EB:
        return fmt.Sprintf("%.2fEB", b/EB)
    case b >= PB:
        return fmt.Sprintf("%.2fPB", b/PB)
    case b >= TB:
        return fmt.Sprintf("%.2fTB", b/TB)
    case b >= GB:
        return fmt.Sprintf("%.2fGB", b/GB)
    case b >= MB:
        return fmt.Sprintf("%.2fMB", b/MB)
    case b >= KB:
        return fmt.Sprintf("%.2fKB", b/KB)
    }
    return fmt.Sprintf("%.2fB", b)
}
  • iota will be cleared every time it encounters a const
  • The default is to start from 0, so the (- = iota) above means to discard the first data with 0
  • In const set, iota increases gradually from top to bottom. The iota value in case 1 < < (10 * iota) is 1, so in fact, 1 shifts 10 bits to the left, which is equal to 1024, and MB shifts 20 bits to the left. And so on to know YB.

Common template cases

const (
            a = iota   //0
            b          //1
            c          //2
            d = "ha"   //Independent value, iota += 1
            e          //"ha"   iota += 1
            f = 100    //iota +=1
            g          //100  iota +=1
            h = iota   //7. Resume counting
            i          //8
    )

The result is

0 1 2 ha ha 100 100 7 8

Tags: Go

Posted on Wed, 01 Sep 2021 15:50:29 -0400 by primefalcon