Go Basics

Infrastructure

In Go language, the infrastructure is as follows:

package main
// When the file is used as an executable instead of a module, it must be imported into main

import "fmt"

// Only global identifiers such as variables, constants and function names can be written outside the entry function

func main(){
	fmt.Println("HELLO,WORLD") // All the code is written in the main entry function
}

Annotation method

In Go language, the annotation method is unified as / /.

Naming method

In GO language, the naming of identifiers must be composed of letters, numbers and underscores.

And cannot start with a number.

GO language is more recommended to use the naming method of small hump.

var userName string // The first word is lowercase and the other words are capitalized

keyword

Do not use keywords as identifiers.

Keyword refers to a predefined identifier with special meaning in the programming language. There are 25 reserved words 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

Reserved word

Do not use reserved words as identifiers.

There are 37 reserved words in Go language.

    Constants:    true  false  iota  nil

        Types:    int  int8  int16  int32  int64  
                  uint  uint8  uint16  uint32  uint64  uintptr
                  float32  float64  complex128  complex64
                  bool  byte  rune  string  error

    Functions:   make  len  cap  new  append  copy  close  delete
                 complex  real  imag
                 panic  recover

Declaration method

Global declaration

The identifier declared outside the entry function is the global declaration.

Globally declared identifiers can be left unused in programs so that no exceptions are thrown.

package main

import "fmt"

var userName string  // Global declaration

func main(){
	fmt.Println("HELLO,WORLD")
}

Local declaration

The identifiers declared in the entry function are all local declarations.

The locally declared identifier must be used. If it is not used, an exception will be thrown.

This is to prevent the problem that the compiled executable file is too large.

package main

import "fmt"

func main(){
	var userName string // Local declaration
	//  .\t1.go:6:6: userName declared but not used
	fmt.Println("HELLO,WORLD")
}

Variable correlation

Declare a variable using the keyword var

Standard statement

The format of the standard declaration is as follows:

var Variable name variable type

As follows, declare a variable of userName of type string.

var userName string

Batch declaration

You can use batch declarations to declare multiple variables.

Batch declaration is made as follows.

package main

import "fmt"

var (
	userName string
	userAge int8
	userGender bool
)

func main() {
	fmt.Println("HELLO,WORLD")
}

Variable setting

You can assign values to variables at the time of declaration.

package main

import "fmt"

var (
	userName string = "Mr. yunya"
)

func main() {
	fmt.Println(userName)
}

Type derivation

Instead of specifying the type, let the variable value after = determine the type of the variable.

package main

import "fmt"

var (
	userName = "Mr. yunya"
)

func main() {
	fmt.Printf("Variable type:%T\n Variable value:%v", userName, userName)
	// Variable type: string
	// Variable value: Mr. yunya
}

Short variable

You can use: = instead of var.

Note: short variable declaration can only be written locally

package main

import "fmt"


func main() {
	userName := "Mr. yunya"
	fmt.Printf("Variable type:%T\n Variable value:%v", userName, userName)
	// Variable type: string
	// Variable value: Mr. yunya
}

Anonymous variable

Because locally declared variables must be used, but sometimes we don't want to use some variables.

If the deconstruction assigns multiple return values of the function, and one of the variables is useless, we can use it at this time_ Use it as an anonymous variable.

  

In other words, anonymous variables will not throw exceptions even if they are not used after being defined locally.

package main

import "fmt"

func f1() (string, string) {
	return "Return value 1", "Useless return value"
}

func main() {
	v1, _ := f1()
	fmt.Println(v1)
}

Duplicate definition

Under the same scope, it is forbidden to define the same variable repeatedly.

package main

import "fmt"

func f1() (string, string) {
	return "Return value 1", "Useless return value"
}

func main() {
	v1 := "Value 1"
	var v1 string = "Value 2"
	fmt.Println(v1)
// 	# command-line-arguments
// .\t1.go:11:6: v1 redeclared in this block
//         previous declaration at .\t1.go:10:2
}

Constant correlation

Declare that a constant uses the keyword const. The value in the constant cannot be changed again. Once defined, it cannot be modified.

Moreover, constants must be assigned values when they are defined! Otherwise, an exception will be thrown

Standard definition

The format of the standard declaration is as follows:

const Constant name constant type = constant value

As follows, declare a variable of userName of type string.

const pi float64 = 3.1415926535897

Batch definition

You can use batch definitions to declare and define multiple constants.

Batch definition is as follows

package main

import "fmt"
const (
	pi float64 = 3.1415926535879
	height int32 = 122
	age int8 = 18
)

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

Definition of saving value

When using batch definition constants, if only the first output is given a value and other constants are not given a value.

Subsequent constants will automatically reference the value of the previous constant.

package main

import "fmt"
const (
	v1 = 100
	v2
	v3
)

func main() {
	fmt.Println(v1) // 100
	fmt.Println(v2) // 100
	fmt.Println(v3) // 100
}

iota

iota is a constant counter in Go language, which can only be used when defining constants.

iota will be reset to 0 when const keyword appears.

Each new row constant declaration in const will make iota count once (iota can be understood as the row index in const statement block).

Using iota simplifies the definition and is useful in defining enumerations.

package main

import "fmt"
const (
	v1 = iota
	v2
	v3
)

func main() {
	fmt.Println(v1) // 0
	fmt.Println(v2) // 1
	fmt.Println(v3) // 2
}

Interview questions

Use_ Skip some values

package main

import "fmt"
const (
	v1 = iota
	_
	v2
	v3
)

func main() {
	fmt.Println(v1) // 0
	fmt.Println(v2) // 2
	fmt.Println(v3) // 3
}

iota announced to jump the queue in the middle

package main

import "fmt"
const (
	v1 = iota
	v2
	v3
)
const v4 = 100 // const iota reset occurs again
const v5 = iota

func main() {
	fmt.Println(v1) // 0
	fmt.Println(v2) // 1
	fmt.Println(v3) // 2
	fmt.Println(v4) // 100
	fmt.Println(v5) // 0
}

When multiple iota s are defined in one line, they will not be added. They will be added only when a new line of code is added (not empty).

const (
		a, b = iota + 1, iota + 2 //1,2
		c, d                      //2,3
		e, f                      //3,4
	)

Define the order of magnitude (here < < represents the shift left operation, and 1 < < 10 represents the shift of the binary representation of 1 by 10 bits to the left, that is, from 1 to 100000000, that is, 1024 in the decimal system. Similarly, 2 < < 2 represents the shift of the binary representation of 2 by 2 bits to the left, that is, from 10 to 1000, that is, 8 in the decimal system.)

const (
		_  = iota
		KB = 1 << (10 * iota)
		MB = 1 << (10 * iota)
		GB = 1 << (10 * iota)
		TB = 1 << (10 * iota)
		PB = 1 << (10 * iota)
	)

fmt Foundation

There are three types of printing in the fmt package.

Print

Print only prints, does not wrap, and cannot format.

package main

import "fmt"

func main() {
	fmt.Print("hello,")
	fmt.Print("world!")
	// hello,world!
}

Printf

Printf can be formatted without line wrapping.

package main

import "fmt"

func main() {
	number := 100
	fmt.Printf("octal number system:%o", number)
	fmt.Printf("decimal system:%0x", number)
	// Octal: 144 decimal: 64
}

Println

Println can wrap lines, but cannot format.

package main

import "fmt"

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

Print format

The following examples show some commonly used print formats in Go language. Other print formats have been introduced in other programming language classifications.

placeholder explain
%v Default format representation of values
%+v Similar to%v, but the field name will be added when outputting the structure
%#v Go syntax representation of value
%T Type of print value
%% Percent sign

Other contents

Other contents will be listed in detail in subsequent articles and fmt standard library.

Tags: Go

Posted by Daniel0 on Sat, 14 May 2022 01:39:03 +0300