Full analysis of built-in types in Go language: full-dimensional exploration from Boolean to string

1. Boolean type

Definition

In the Go language, the Boolean type is represented by the keyword bool , which has two predefined constant values: true strong> andfalse.

var myBool bool = true

Basic usage

Declaration and Initialization

Boolean variables can be initialized when declared or assigned a value later.

//Declare and initialize
var isReady bool = true

//Assign value after declaration
var isEnabled bool
isEnabled = false

Logical operation

The Boolean type is mainly used for logical operations: AND ( & amp; & amp;), OR (|| ), and NOT (!).

// AND operation
result := true & amp; & amp; false // Output: false

//OR operation
result = true || false // Output: true

// NOT operation
result = !true // output: false

Advanced usage

Conditional statement

Boolean types are often used in the if, else if and else structures.

if isReady {
    fmt.Println("System is ready.")
} else {
    fmt.Println("System is not ready.")
}

Loop structure

Boolean expressions can also be used to control looping structures such as for.

for isReady {
    //Execute code
}

Function return value

The Boolean type is also often used as the return type of a function to indicate whether the function executed or verified successfully.

func isAuthenticated() bool {
    // Authentication logic
    return true
}

Common Mistakes and Pitfalls

  1. Zero value: The zero value of Boolean type is false. Please note that uninitialized Boolean variables default to false code>.
  2. Type conversion: The Go language does not allow implicit conversions between boolean types and other types (such as integers).

Two, integer types

Definition

In the Go language, integer types are mainly divided into two categories: signed (Signed) and unsigned (Unsigned) integers, and there is also a special integer type rune andbyte.

  • Signed integers: int8, int16, int32 >, int64, int
  • Unsigned integers: uint8, uint16, uint32 >, uint64, uint
  • Special integers: rune (equivalent to int32), byte < /strong>(Equivalent to uint8)

Basic usage

Declaration and Initialization

//Declare and initialize signed integers
var a int8 = -128
var b int32 = 2147483647

// Declare and initialize unsigned integer
var c uint8 = 255
vard uint32 = 4294967295

operator

Commonly used integer operators include: addition ( + ), subtraction (-), multiplication ( *), divide (/) and modulo (% ).

//Integer operations
x := 10
y := 20
result := x + y // The result is 30

Bit operation

Integers also support bitwise operations: AND ( & amp;), OR (|), XOR (^), as well as bit-left shift (<<) and bit-right shift (>> ).

//bit operations
var m uint8 = 1 << 3 // Result is 8

Advanced usage

data overflow

It should be noted that the integer type has a range limit, and exceeding the range will cause data overflow.

var maxInt8 int8 = 127
maxInt8 = maxInt8 + 1 // Overflow, the result is -128

Type conversion

When converting between different types, type conversion needs to be explicitly used.

var integer16 int16 = 32767
var integer32 int32

integer32 = int32(integer16) // type conversion

Type inference

The Go language automatically infers types when using := for variable declaration and initialization.

autoInt := 42 // Type inference is int

Special integer type

rune

The rune type is often used to represent a Unicode character.

var character rune = 'A'

byte

The byte type is usually used to process ASCII characters or binary data.

var b byte = 'a'

FAQs and Pitfalls

  1. Type mismatch: Different integer types cannot be directly operated on.
  2. Data overflow: You need to pay attention to data overflow issues when performing arithmetic operations.

Three, floating-point number types

Definition

In the Go language, there are two main types of floating point numbers:

  • float32: 32-bit floating point number with approximately 7 decimal places of precision.
  • float64: A 64-bit floating point number with approximately 15 decimal places of precision.

Basic usage

Declaration and Initialization

//Declare and initialize float32 and float64
var a float32 = 3.14
var b float64 = 3.141592653589793

Common operations

Commonly used operators include: addition ( + ), subtraction (-), multiplication (*), except (/).

x := 1.1
y := 2.2
result := x + y // The result is 3.3

Advanced usage

Accuracy Issue

There are accuracy issues due to limitations in the computer's internal representation of floating point numbers.

//Accuracy issue
var c float32 = 0.1
var d float32 = 0.2
var float32 = 0.3

if c + d == e {
    fmt.Println("Equal")
} else {
    fmt.Println("Not Equal") // Output "Not Equal"
}

Mathematical function

The Go language's math package provides a rich set of mathematical functions.

import "math"

// square root
result := math.Sqrt(16.0) // The result is 4.0

Type conversion and inference

//Type conversion
var f float32 = 1.1
var g float64
g = float64(f) // type conversion

// type inference
autoFloat := 3.14 // Go language will automatically infer float64 type

Special circumstances

Indicates infinity and NaN

//infinity
var inf float64 = math.Inf(1)

// NaN (Not a Number)
var nan float64 = math.NaN()

Conversion with integers

NOTE: There may be a loss of precision when converting.

var h float64 = 3.9
var i int = int(h) // Result is 3

FAQs and Pitfalls

  1. Precision issues: When performing floating-point operations, you need to pay attention to precision issues.
  2. Type conversion: Be aware of the loss of precision when converting between integers and floating point numbers.

4. String type

Definition

In Go language, the string type is defined as an immutable sequence of bytes, usually used to store text data.

//Declare a variable of string type
var str string

Basic usage

Declaration and initialization

//Declare and initialize a string
var hello string = "Hello, world!"

Or use short variable declarations:

hello := "Hello, world!"

Common operations

String concatenation:

str1 := "Hello"
str2 := "World"
result := str1 + ", " + str2 // Result: "Hello, World"

Get the string length:

length := len("Hello, World!") // Result: 13

Advanced usage

String and byte slice

In Go, it's easy to convert between strings and byte slices.

//Convert string to byte slice
byteSlice := []byte("Hello")

// Convert byte slice to string
str := string(byteSlice)

String interception

//Intercept some characters in the string
subStr := "Hello, World!"[7:12] // Result: "World"

String traversal

// Traverse each character in the string
for i, r := range "Hello" {
    fmt.Printf("%d: %c\
", i, r)
}

Output:

0: H
1:e
2:l
3: l
4:o

Special usage

Multi-line string

Use backticks ( ` ) to declare a multiline string.

multiLineStr := `This is
a multi-line
string.`

escape character

Go strings support a variety of escape characters, such as \
(line feed), \t (tab symbol) etc.

//Use escape characters
escapedStr := "This is a line.\
This is another line."

FAQs and Pitfalls

  1. Immutability: Go strings are immutable, any attempt to change the contents of a string will create a new string.
  2. Unicode and UTF-8: Go strings use UTF-8 encoding by default, which means a string may contain characters of many different lengths.

5. Other features

In the previous chapters, we explored Go’s various built-in types in detail: from booleans to integers, floats, and strings. These basic types form the foundation of the Go language and are important for writing performant and maintainable code.

Simpleness and efficiency of the type system

The Go language's type system is relatively simple, but that doesn't mean it's not powerful or flexible. On the contrary, the Go language provides a very efficient and easy-to-understand type mechanism.

var isActive bool // Boolean type
var price int32 // integer type
var pi float32 // Floating point number type
var name string // string type

Why immutability is important

In Go, strings are immutable, which facilitates multi-threaded programming. Immutability ensures that the state of data is always predictable when accessed concurrently.

//String immutability example
str := "immutable"
// str[0] = 'I' // Compilation error

Performance and Optimization

Go provides a large number of built-in functions and standard libraries to optimize various types of operations.

import "math"

// Floating point optimization
result := math.Floor(3.75) // Output: 3.0

Other

  1. Type aliases and custom types: Go allows you to create type aliases and custom types, which are very useful for writing domain-specific code.
  2. Strict type checking: Go's compiler performs strict type checking, which greatly reduces runtime errors.
  3. Reduce conversions: Go’s type inference and interface mechanism reduce unnecessary type conversions.
syntaxbug.com © 2021 All Rights Reserved.