Basic data types of go language foundation

Time:2021-5-7

Go language has a wealth of data types, in addition to the basic integer, floating-point, Boolean, string, as well as array, slice, structure, function, map, channel and so on. The basic types of go language are similar to other languages.

Basic data type

integer

Integers can be divided into the following two categories: int8, int16, int32, Int64 by length, and corresponding unsigned integers: uint8, uint16, uint32, Uint64

Among them,uint8That’s what we knowbyteType,int16Corresponding to C languageshortType,int64Corresponding to C languagelongType.

type describe
uint8 Unsigned 8-bit integer (0 to 255)
uint16 Unsigned 16 bit integer (0 to 65535)
uint32 Unsigned 32-bit integer (0 to 4294967295)
uint64 Unsigned 64 bit integer (0 to 18446744073709551615)
int8 Signed 8-bit integer (- 128 to 127)
int16 Signed 16 bit integers (- 32768 to 32767)
int32 Signed 32-bit integers (- 2147483648 to 2147483647)
int64 Signed 64 bit integer (- 9223372036854775808 to 922337203685475807)

Special integer

type describe
uint It’s on 32-bit operating systemsuint32On 64 bit operating systemuint64
int It’s on 32-bit operating systemsint32On 64 bit operating systemint64
uintptr An unsigned integer used to hold a pointer

be careful:in useintanduintType, you cannot assume that it is a 32-bit or 64 bit integer, but considerintanduintPossible differences on different platforms.

matters needing attentionGets the built-in length of the objectlen()The length returned by the function can vary according to the byte length of different platforms. In practical use, the number of elements of slice or map can be usedintTo express. When it comes to binary transmission, read-write file structure description, in order to keep the file structure will not be affected by the byte length of different compilation target platform, do not useintanduint

Number literals syntax

After go1.13, the literal number syntax is introduced to facilitate developers to define numbers in binary, octal or hexadecimal floating-point format, such as:

V: = 0b000101101, representing 101101 in binary system, equivalent to 45 in decimal system. V: = 0o377, representing 377 in octal system, equivalent to 255 in decimal system. V: = 0x1p-2, representing 1 divided by 2 in hexadecimal ², That’s 0.25. And it allows us to use it_ To separate numbers, for example:

v := 123_ 456 equals 123456.

We can use the FMT function to display an integer in different decimal forms.

package main
 
import "fmt"
 
func main(){
	//Decimal system
	var a int = 10
	fmt.Printf("%d \n", a)  // 10
	FMT. Printf (% B / N ", a) // 1010 placeholder% B represents binary
 
	//Octal starts with 0
	var b int = 077
	fmt.Printf("%o \n", b)  // 77
 
	//Hexadecimal starts with X
	var c int = 0xff
	fmt.Printf("%x \n", c)  // ff
	fmt.Printf("%X \n", c)  // FF
}

float

Go language supports two kinds of floating-point numbersfloat32andfloat64. The two floating-point data formats follow theIEEE 754Standard:float32The maximum range of floating-point numbers for is about3.4e38, you can use constant definitions:math.MaxFloat32float64The maximum range of floating-point numbers for is about1.8e308, you can use a constant definition:math.MaxFloat64

When printing floating-point numbers, you can use thefmtBag verb%fThe code is as follows:

package main
import (
        "fmt"
        "math"
)
func main() {
        fmt.Printf("%f\n", math.Pi)
        fmt.Printf("%.2f\n", math.Pi)
}

complex

Complex64 and complex128

var c1 complex64
c1 = 1 + 2i
var c2 complex128
c2 = 2 + 3i
fmt.Println(c1)
fmt.Println(c2)

Complex number has real part and imaginary part. The real part and imaginary part of complex64 are 32 bits, and the real part and imaginary part of complex128 are 64 bits.

Boolean value

In go languageboolType to declare Boolean data, which has onlyTrue (true)andFalse (false)Two values.

be careful:

  1. The default value for boolean type variables isfalse
  2. Cast integer to Boolean is not allowed in go language
  3. Boolean cannot participate in numeric operations and cannot be converted to other types.

character string

In go, strings appear as native data types, just like other native data types (int, bool, float32, float64, etc.). The internal implementation of string in go languageUTF-8code. The value of the string isDouble quotation marks (")You can directly add non ASCII characters to the source code of go language, for example:

s1 := "hello"
S2: "hello"

String escape character

Common escape characters of go language strings include carriage return, newline, single and double quotation marks, tab, etc., as shown in the following table.

Escape character meaning
\r Carriage return (return to the beginning of the line)
\n Line feed (jump directly to the same column position of the next line)
\t Tab
\' Single quotation mark
\" Double quotation marks
\\ Backslash

For example, we want to print a file path on the windows platform

package main
import (
    "fmt"
)
func main() {
    fmt.Println("str := \"c:\\Code\\lesson1\\go.exe\"")
}

Multiline string

To define a multiline string in go, you must usebackquote Character:

S1: ='the first line
The second line
The third line
`
fmt.Println(s1)

The line break between the back quotation marks will be used as the line break in the string, but all escape characters are invalid, and the text will be output as is.

Common operations of string

method introduce
len(str) Find the length
+Or fmt.sprintf Splicing strings
strings.Split division
strings.contains Judge whether to include
strings.HasPrefix,strings.HasSuffix Prefix / suffix judgment
strings.Index(),strings.LastIndex() The position where the substring appears
strings.Join(a[]string, sep string) Join operation

Byte and run types

The elements that make up each string are called “characters”, which can be obtained by traversing or obtaining a single string element. The characters are wrapped in single quotation marks (‘)

Var a: ='middle '
var b := 'x'

There are two characters in go language

  1. uint8Type, or byte type, representsASCII codeA character of.
  2. runeType, representing aUTF-8 characters

When you need to deal with Chinese, Japanese or other compound characters, you need to useruneType.runeType is actually aint32

Go uses a special run type to process Unicode, which makes the text processing based on Unicode more convenient. It can also use byte type to process the default string, which has good performance and scalability.

//Traversal string
func traversalString() {
	S: "Hello Shahe"
	for i := 0; i < len(s); i++ { //byte
		fmt.Printf("%v(%c) ", s[i], s[i])
	}
	fmt.Println()
	for _, r := range s { //rune
		fmt.Printf("%v(%c) ", r, r)
	}
	fmt.Println()
}

Output:

104(h) 101(e) 108(l) 108(l) 111(o) 230(æ) 178(²) 153() 230(æ) 178(²) 179(³) 
104 (H) 101 (E) 108 (L) 108 (L) 111 (o) 27801 (sand) 27827 (River)

Because the next Chinese character encoded by utf8 is composed of 3-4 bytes, we can’t simply traverse a string containing Chinese characters by bytes, otherwise the result of the first line in the above output will appear.

The bottom layer of string is a byte array, so it can be combined with[]byteType conversion. The string cannot be modified. The string is composed of byte, so the length of the string is the length of byte. Rune type is used to represent utf8 characters. A rune character consists of one or more bytes.

Modify string

func changeString() {
	s1 := "big"
	//Force type conversion
	byteS1 := []byte(s1)
	byteS1[0] = 'p'
	fmt.Println(string(byteS1))

	S2: "white radish"
	runeS2 := []rune(s2)
	Runes2 [0] ='Red '
	fmt.Println(string(runeS2))
}

To modify a string, you need to convert it to[]runeor[]byteAnd then convert tostring. Either way, memory is reallocated and the byte array is copied.

Type conversion

There is only mandatory type conversion in go language, but no implicit type conversion. This syntax can only be used when conversions between two types are supported.

The basic syntax of cast is as follows:

T (expression)

Where t is the type to convert. Expressions include variables, complex operators and function return values

For example, when calculating the length of the hypotenuse of a right triangle, we use the sqrt() function of math package, which receives parameters of float64 type, while variables A and B are of int type. At this time, we need to convert a and B to float64 type.

func sqrtDemo() {
	var a, b = 3, 4
	var c int
	//The parameter received by math. Sqrt() is of type float64 and needs to be cast
	c = int(math.Sqrt(float64(a*a + b*b)))
	fmt.Println(c)
}

Exercises

  1. Write code to define an integer, floating-point, Boolean, string variable, usefmt.Printf()collocation%TPrint out the values and types of the above variables respectively.
  2. Write code statistics string"Hello little prince of Shahe"The number of Chinese characters in Chinese.

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]