Go (2) basic data types

        There are rich data types in the Go language. In addition to basic integers, floating-point types, Boolean types, and strings, there are also arrays, slices, structures, functions, maps, and channels. The basic types of Go language are similar to other languages.

Table of contents

basic data type

integer

 special integer

Number literals syntax

floating point

plural

Boolean value

string

 string escape character

multiline string

Common operations on strings

byte and rune types

modify string

type conversion


basic data type

integer

Integers fall into two broad categories:

  • Divided by length: int8, int16, int32, int64
  • Corresponding unsigned integer types: uint8, uint16, uint32, uint64

        Among them, uint8is the type we are familiar with byte, int16corresponding to the type in the C language short, int64corresponding to the type in the C language long.

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)
you8 signed 8-bit integer (-128 to 127)
int16 signed 16-bit integer (-32768 to 32767)
int32 Signed 32-bit integer (-2147483648 to 2147483647)
int64 Signed 64-bit integer (-9223372036854775808 to 9223372036854775807)

 special integer

type describe
uint On 32-bit OS uint32, on 64-bit OSuint64
int On 32-bit OS int32, on 64-bit OSint64
uintptr Unsigned integer, used to store a pointer

Note:  When using the intand  uinttype, you cannot assume that it is a 32-bit or 64-bit integer, but consider the difference intthat uintthe sum may have on different platforms.

Note: The length returned by the built-in function to get the length of an object len()can vary according to the byte length of different platforms. In actual use, the number of elements in slices or maps can intbe used to represent. When it comes to the structure description of binary transmission, reading and writing files, in order to keep the structure of the file from being affected by the byte length of different compilation target platforms, do not use intand  uint.

Number literals syntax

After the Go1.13 version, the number literal syntax was introduced, which is convenient for developers to define numbers in the format of binary, octal or hexadecimal floating point numbers, for example:

v := 0b00101101, which represents 101101 in binary, which is equivalent to 45 in decimal. v := 0o377, representing 377 in octal, which is equivalent to 255 in decimal. v := 0x1p-2, representing 1 in hexadecimal divided by 2², which is 0.25.

And it also allows us _ to  separate numbers, for example: v := 123_456 the value of v is equal to 123456.

We can use the fmt function to display an integer in different base forms.

package main
 
import "fmt"
 
func main(){
	// 十进制
	var a int = 10
	fmt.Printf("%d \n", a)  // 10
	fmt.Printf("%b \n", a)  // 1010  占位符%b表示二进制
 
	// 八进制  以0开头
	var b int = 077
	fmt.Printf("%o \n", b)  // 77
 
	// 十六进制  以0x开头
	var c int = 0xff
	fmt.Printf("%x \n", c)  // ff
	fmt.Printf("%X \n", c)  // FF
}

floating point

The Go language supports two types of floating-point numbers: float32and float64. These two floating-point data formats follow IEEE 754the standard:  float32 The maximum range of floating-point numbers is approx.  3.4e38, which can be defined using the constant: math.MaxFloat32float64 The maximum range of floating-point numbers is approx  1.8e308. and can be defined using a constant: math.MaxFloat64.

When printing floating-point numbers, you can use fmtpackage verbs %f, the code is as follows:

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

plural

 complex64 and complex128

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

Complex numbers have real and imaginary parts, the real and imaginary parts of complex64 are 32 bits, and the real and imaginary parts of complex128 are 64 bits.

Boolean value

boolBoolean data is declared         by type in Go language , and Boolean data has true(真)only false(假)two values.

Notice:

  1. The default value for Boolean variables is false.
  2. Coercion from integer to boolean is not allowed in Go language.
  3. The Boolean type cannot participate in numerical operations, nor can it be converted to other types.

string

        Strings in the Go language appear as native data types, and using strings is like using other native data types (int, bool, float32, float64, etc.). The internal implementation of strings in Go uses UTF-8encodings. The value of the string 双引号(")is the content in , you can directly add non-ASCII characters in the source code of the Go language, for example:

s1 := "hello"
s2 := "你好"

 string escape character

Common escape characters for strings in the Go language include carriage return, line feed, single and double quotes, tabs, etc., as shown in the following table.

Escapes meaning
\r Carriage return (return to the beginning of the line)
\n Line break (jump directly to the same column position on the next line)
\t Tabs
\' apostrophe
\" Double quotes
\\ backslash

For example, we want to print a file path under a Windows platform:

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

multiline string

When defining a multi-line string in Go language, characters must be used 反引号:

s1 := `第一行
第二行
第三行
`
fmt.Println(s1)

Newlines between backticks will be treated as newlines in the string, but any escape characters will have no effect, and the text will be output as-is.

Common operations on strings

method introduce
only Find the length
+ or fmt.Sprintf concatenate string
strings.Split Split
strings.contains Determine whether to include
strings.HasPrefix,strings.HasSuffix Prefix/Suffix Judgment
strings.Index(),strings.LastIndex() where the substring occurs
strings.Join(a[]string, sep string) join operation

byte and rune types

        The elements that make up each string are called "characters", and characters can be obtained by traversing or obtaining a single string element. Characters are enclosed in single quotes ('), such as:

var a = '中'
var b = 'x'

There are two types of characters in the Go language:

  1. uint8Type, or byte type, represents a ASCII码character.
  2. runetype, representing a  UTF-8字符.

        When dealing with Chinese, Japanese or other compound characters, you need to use runethe type. runeThe type is actually one int32.

        Go uses a special rune type to process Unicode, which makes Unicode-based text processing more convenient. It can also use byte type for default string processing, which takes care of performance and scalability.

// 遍历字符串
func traversalString() {
	s := "hello沙河"
	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(沙) 27827(河) 

        Because the next Chinese character in UTF8 encoding consists of 3~4 bytes, we cannot simply traverse a character string containing Chinese according to the bytes, otherwise the result of the first line in the above output will appear.

        The bottom layer of the string is a byte array, so it can be []byteconverted to and from the type. Strings cannot be modified. Strings are composed of byte bytes, so the length of the string is the length of byte bytes. The rune type is used to represent utf8 characters, and a rune character consists of one or more bytes.

modify string

        To modify a string, you need to convert it to []runeor []byteafter you're done string. With either conversion, the memory is reallocated, and the byte array is copied.

func changeString() {
	s1 := "big"
	// 强制类型转换
	byteS1 := []byte(s1)
	byteS1[0] = 'p'
	fmt.Println(string(byteS1))

	s2 := "白萝卜"
	runeS2 := []rune(s2)
	runeS2[0] = '红'
	fmt.Println(string(runeS2))
}

type conversion

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

The basic syntax of mandatory type conversion is as follows:

T(表达式)

Among them, T represents the type to be converted. Expressions include variables, complex operators, and function return values, etc.

        For example, when calculating the length of the hypotenuse of a right triangle, use the Sqrt() function of the math package. This function receives a parameter of type float64, and the variables a and b are both of type int. At this time, it is necessary to cast a and b into types It is of float64 type.

func sqrtDemo() {
	var a, b = 3, 4
	var c int
	// math.Sqrt()接收的参数是float64类型,需要强制转换
	c = int(math.Sqrt(float64(a*a + b*b)))
	fmt.Println(c)
}

Guess you like

Origin blog.csdn.net/qq_54729417/article/details/127822155