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

Directory

  • 1. Boolean type
    • definition
    • Basic usage
      • Declaration and initialization
      • logic operation
    • Advanced usage
      • Conditional statements
      • Loop structure
      • function return value
    • Common mistakes and pitfalls
  • 2. Integer type
    • definition
    • Basic usage
      • Declaration and initialization
      • operator
      • Bit operations
    • Advanced usage
      • Data overflow
      • type conversion
      • type inference
    • Special integer types
      • rune
      • byte
    • Frequently asked questions and pitfalls
  • 3. Floating point type
    • definition
    • Basic usage
      • Declaration and initialization
      • Common operations
    • Advanced usage
      • Accuracy issue
      • Math functions
      • Type conversion and inference
    • Special case
      • Represents infinity and NaN
      • Conversions to integers
    • Frequently asked questions and pitfalls
  • 4. String type
    • definition
    • Basic usage
      • Declaration and initialization
      • Common operations
    • Advanced usage
      • String and byte slicing
      • String interception
      • String traversal
    • Special usage
      • multiline string
      • escape character
    • Frequently asked questions and pitfalls
  • 5. Other characteristics
    • The simplicity and efficiency of the type system
    • Why immutability matters
    • Performance and Optimization
    • other

Follow the WeChat public account [TechLeadCloud] to share full-dimensional knowledge of Internet architecture and cloud service technology. The author has 10+ years of Internet service architecture, AI product development experience, and team management experience. He holds a master’s degree from Tongji University in Fudan University, a member of Fudan Robot Intelligence Laboratory, a senior architect certified by Alibaba Cloud, a project management professional, and research and development of AI products with revenue of hundreds of millions. principal.

This article deeply explores the built-in type system of the Go language, from Boolean types to complex string types. It aims to provide developers with comprehensive and detailed guidance. Through rich code examples and application scenarios, it reveals how to use it efficiently in actual projects. use these types.

In programming, a type can be thought of as a template for a value, and a value can be thought of as an instance of the type. In this article, we focus on introducing the built-in (or pre-declared) basic types of the Go language and their literal representations. Combination types are not involved here.

file

1. Boolean type

Definition

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

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 operations

Boolean types are 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 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.
  2. Type conversion: The Go language does not allow implicit conversions between boolean types and other types (such as integers).

2. Integer type

Definition

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

  • Signed integers: int8, int16, int32, int64, int
  • Unsigned integers: uint8, uint16, uint32, uint64, uint
  • Special integers: rune (equivalent to int32), byte (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 (*), division (/) and module (%).

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

Bit operations

Integers also support bitwise operations: AND ( & amp;), OR (|), XOR (^), and left bit 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 types

rune

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

var character rune = 'A'

byte

The byte type is usually used to handle 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.

3. Floating point type

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: 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 (*), division (/ code>).

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 e float32 = 0.3

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

Mathematical functions

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

Represents infinity and NaN

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

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

Conversion to 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 slices

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

Multiline 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 \
(newline), \t (tab), 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.

Simple and efficient 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

Others

  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.

Follow the WeChat public account [TechLeadCloud] to share full-dimensional knowledge of Internet architecture and cloud service technology. The author has 10+ years of Internet service architecture, AI product development experience, and team management experience. He holds a master's degree from Tongji University in Fudan University, a member of Fudan Robot Intelligence Laboratory, a senior architect certified by Alibaba Cloud, a project management professional, and research and development of AI products with revenue of hundreds of millions. principal.