Notes on go language learning (2)


1、 Character

1. Overview

  • The character type stores a single letter or a single text
  • Go language does not support character type. In go language, all character values are converted to int32 values in corresponding encoding table
  • Go language uses utf8 encoding by default

2. Coding history

  • At the beginning, eight on-off transistors were used to represent everything in the world. This is the origin of bytes. Later, machines that can control bytes appearedcomputer
  • Call 32 in byte asControl codeAfter that, space, punctuation, numbers, upper and lower case letters are added on the basis of the control code until 127, finally forming the AsniASCII codeThis is already a good support for English
  • With the application of computers in the world, new letters, symbols, horizontal lines and vertical lines have been added to the original ASCII to 255, which is called “255”Extended character setBut the computer is still supporting English
  • When China began to use computers, in order to support Chinese, the former 127 numbers were reserved, which were calledHalf angleThe latter part is the full angle, of which 6763 Chinese characters meet the requirements of most Chinese situationsGB2312
  • With the popularity of computers in China, some Chinese characters cannot be typed when using GB2312. On the basis of GB2312, nearly 20000 Chinese characters (including traditional Chinese characters and symbols) have been addedGBKLater, in order to support the ethnic minorities, they withdrew on the basis of GBKGB18080
  • Each country in the world has its own set of codes. In order to unify the standards, ISO international redefines a set of codes, hoping to include all the characters and symbols in the worldUnicode
  • With the rapid development of the Internet, in order to alleviate the problem of traffic waste in the transmission of Unicode network, the emergence ofUTF codingThere are two kinds of UTF-8 (8-bit transmission) and utf-16 (16 bit transmission). Among them, UTF-8 is the most widely used, which is a variable length encoding mode, and Chinese takes up 3 bytes

2、 Escape character

1. Introduction to escape characters

  • In go language, you can use% + specific letters to form escape characters, which means that a combination of specific meanings becomes escape characters

  • It is also called verb in go language

  • Escape characters are frequently used in go language in the following two situations

fmt.Print ("verb", content) // output
fmt.Scanf ("verb", accept variable) // input

2. Decimal description

  • Base number is often encountered in programming, the number is divided into binary, octal, decimal, hexadecimal, in which decimal is usually the most common contact
  • The x-base system meets the following requirements:
    • Full x into one
    • Max X-1 per person
    • The nth digit represents the (n-1) power of X
  • In hexadecimal system, a = 10, B = 11, C = 12, d = 13, e = 14, f = 15

3. Summary of common escape characters

Verb meaning
%d Decimal integer
%x、%X Show hexadecimal integers in case
%o Octal integer
%b Binary integer
%f、%g、%e Floating point number
%t Boolean value
%c character
%s character string
%q Double quoted string
%v Built in format content
%T type
%p Memory address
%% Character%
\n Line break
\t indent

3、 User input

1. Introduction

  • User input is often used in practice
  • When the program is running, the program will block until it receives the user’s input. After the user enters, the program will continue to run after assigning the content to the corresponding variable
    • In go language, there are multiple ways to accept user input, and the scan function using FMT package is the simplest

2. Several ways of receiving user input

  • Use scanln (& variable name, & variable name) to receive

    • All entries must be on the same line
    • Each content is separated by a space
    • Enter after line feed means stop input
    • If you want to receive 3 values and only enter 2 values in the console, press enter to stop receiving
    • If you want to receive 2 values and enter 3 values in the console, you can only receive two values after press enter
package main
import "fmt"
func main() {
	var name, age string
	fmt.Print ("please enter user name and age:)
	fmt.Scanln(&name, &age)
	fmt.Println ("received content is:", name, age)
  • It can also be used fmt.Scanf (verb, & variable) is entered in a specific format

    • The following example demonstrates one entry per newline
package main
import "fmt"
func main() {
   var a, b string
   fmt.Println ("please enter name and age):"
   fmt.Scanf("%s\n%s", &a, &b)
   fmt.Printf("%s\n%s", a, b)
  • It should be noted that if two strings are entered in the same row with a space between them, the compiler cannot split the input

4、 Output

1. Printout

  • Output is used frequently in the program. The output statement can output some results to the console during the execution of the program. The programmer can judge whether it meets the expectation through the output result in the console
  • There are multiple output modes in go language. Different output scenarios are different. They can be classified into three categories, and each type can be divided into three types (original content, original content + LN, original content + F)
    • PrintXX()
    • FprintXX()
    • SprintXX()


  • Fprintxx is often used in go web to write the content to the response
  • Take fprintln() as an example, and the source code is as follows:
// Fprintln formats using the default formats for its operands and writes to w.
// Spaces are always added between operands and a newline is appended.
// It returns the number of bytes written and any write error encountered.
func Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
	p := newPrinter()
	n, err = w.Write(p.buf)
  • The first parameter in the function parameter is the output stream, and the following parameter is the content, which means that the content is written to the output stream

  • The first return value represents the length of the output content (bytes), and the second value represents an error. If there is no error, nil is taken

    • Fprintln() will add a newline character after the output, so the length is 1 more than the content
    • The source code of p.doprintln (a) in fprintln() source code
// doPrintln is like doPrint but always adds a space between arguments
// and a newline after the last argument.
func (p *pp) doPrintln(a []interface{}) {
	for argNum, arg := range a {
		if argNum > 0 {
			p.buf.writeByte(' ')
		p.printArg(arg, 'v')
  • Fprintxx () supports the following three ways

    • os.Stdout Represents the console output stream
func main() {
	fmt.Fprint ( os.Stdout , "content 1") // write content to stream
	fmt.Fprintln ( os.Stdout "," content 2 ") // additional line breaks are written after writing content to the stream
	fmt.Fprintf ( os.Stdout ","% s "," content 3 ") // write content to stream according to verb format


  • Printxx supports the following three ways
func main(){
	fmt.Println ("content 1") // line feed after output
	fmt.Print ("content 2") // no line feed after output
	fmt.Printf ("verb", "content") // output the specified format content according to the verb
  • Take println() as an example, and the source code is as follows
// Println formats using the default formats for its operands and writes to standard output.
// Spaces are always added between operands and a newline is appended.
// It returns the number of bytes written and any write error encountered.
func Println(a ...interface{}) (n int, err error) {
   return Fprintln(os.Stdout, a...)
  • We can see that the bottom layer of println() is actually fprintln(), and the return value is still the content length and error information


  • Taking sprintln() as an example, the main differences between sprintln() and println() are as follows:
    • Sprintln () returns the formal result as a string and does not print it to the console
    • Println() prints the results to the console, returning content length and errors
  • So, strictly speaking, sprintxx is not a printout, but more like a string conversion
  • The source code is as follows
// Sprint formats using the default formats for its operands and returns the resulting string.
// Spaces are added between operands when neither is a string.
func Sprint(a ...interface{}) string {
   p := newPrinter()
   s := string(p.buf)
   return s
  • There are also three ways
fmt.Sprint (content 1, content 2)
fmt.Sprintln("1", "2")

5、 Variable declaration and assignment

1. Static language and dynamic language

  • Static typed language and strongly typed language are the same meaning, which means that the type is determined in the compiler, and the type cannot be changed
  • Dynamic typed language and weakly typed language have the same meaning, which indicates what type of variable can be determined in the process of running and the type of variable follows the change

2. Introduction to go language variables

  • Go language, like other languages, has a basic storage container, which can store one or more values in the program. It is convenient for the program to use the contents of the container many times. This container is called a variable
  • Although go language is static typed language, it supports dynamic typed language syntax, because go language expects programmers to declare less variables and increase GC efficiency

3. Variable naming rules

  • Start with a letter or an underline_ At the beginning)
  • It can be followed by any number of characters, numbers, and underscores
  • Case sensitive
  • Can’t be a keyword (keyword has a specific meaning), the following are the keywords of go language
The key words are as follows
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
  • It can be reserved words, but it is not recommended to use reserved words as variable names. The following are reserved words of go language
The reserved words are as follows
true false iota nil int
int8 int16 int32 int64 unit
unit8 unit16 unit32 unitptr float32
float64 complex128 complex64 bool byte
rune string error make len
cap new append copy close
deletecomplex real image panic recover
  • Variables with the same name are not allowed in the same scope
  • Go language requires variables to be used at least once after declaration

4. Single variable declaration and assignment

  • Declaration first and then assignment (memory is opened after declaration, and different types of variables have different initial values)
//1. Statement
Var variable name type
//2. Assignment
Variable name = value
  • Declare and assign (not recommended)
Var variable name type = value

Var Smalling string = "English name"
  • Declare and assign (omit type, variable type depends on value type)
Var variable name = value
  • Short variable (can only be used inside a function)
Variable name: = value

5. Declare multiple variables

  • Declaration before assignment
func main(){
	var a,b,c int
	a,b,c = 1,2,3
  • Assignment on declaration
func main(){
	var a,b,c,d = 1,2,3,false
  • Declaration and assignment, recommended method
func main(){
	var (
		a = 1
		b = true
		C = Test
  • When using short variables to assign values to multiple variables, you must ensure that at least two variables are not declared
func main(){
    var (
        a = 1
        b = true 
        C = Test
    b,c,d := false, "smallming", 3

6、 Integer

1. Overview

  • In go language, the types of data operation can be divided into integer type and floating-point type

  • All integer numbers can be stored in the integer type for mathematical operation

    • Integers and the results of integer operations are still integers (5 / 2 = 2)
    • Both of them are integers, but operations between int8 and int16 are not allowed and must be converted
  • Integers can be divided into coincidence integers and unsigned integers

    • Signed integers have positive and negative numbers. The highest bit of binary system represents sign, 0 is positive, 1 is negative, int and intx are signed integers
  • The signed integer can only take the integer greater than or equal to 0. The highest bit of the binary represents the real number, and unit and unitx are the unsigned integers

  • Range and function of integer value

    • The unified formula of signed integers is: from the N-1 power of – 2 to the N-1 power of 2 minus 1
  • The unified formula for signed integers is

type Value range
int8 [-128,127]
int16 [-32768,32767]
int32 [21474836482147483647], go language has no character type, all characters use int32
int64 [-92233722036854775808,9223372036854775807]
int Limited by the computer system, how many bits is the system and how many bits is the int
unit8 [0,255]
unit16 [0,65535]
unit32 [0,4294967295]
unit64 [0,18446744073709551615]
uint Limited by the computer system, how many bits is the system and how many bits is the uint
rune Similar to int32, it is often used to get the Unicode code of a value
byte Similar to uint8, the emphasis value is raw data, and one byte takes up eight binary bits
uintptr The size is uncertain, similar to the underlying programming

2. Type conversion

  • Go language is a static type language, and it does not have the function of low precision to high precision automatic conversion. Therefore, the mutual assignment of different types of variables requires type conversion
package main

import "fmt"

func main() {
	//Declare 3 type variables
	var a int = 1
	var b int32 = 2
	var c int64 = 3

	fmt.Println(a, b, c)

	//Convert int32 to Int64
	a = int(b)
	fmt.Println(a, b)
	a = 1

	//Convert Int64 to int32
	b = int32(c)
	fmt.Println(b, c)
	b = 2

	//Convert int to Int64
	c = int64(a)
	fmt.Println(a, c)
	c = 3

3. Integers with different base numbers

  • Support octal, decimal, hexadecimal number to create integer, and finally converted to decimal by the system
  • Binary values are not supported
package main

import "fmt"

func main() {
	//The default is decimal
	d := 17

	//The beginning of 0 is octal
	o := 021

	//The beginning of X indicates hexadecimal
	x := 0x11

	//E2 is the second power of 10
	e := 11e2

	fmt.Println(d, o, x, e)

	//Change the contents of variable d into binary
	b := fmt.Sprintf("%b", d)