1 Introduction to Go Language Data Types
In Go language, data types are the foundation of programming, determining the form of data that variables can store. The basic data types provided by Go language are mainly divided into the following categories:
Data Type | Description | Memory Usage |
---|---|---|
bool | Boolean type, used to store true or false | 1 byte |
int, uint | Signed and unsigned integers, default size depends on the system platform | 4 or 8 bytes |
int8, uint8 | 8-bit signed and unsigned integers | 1 byte |
int16, uint16 | 16-bit signed and unsigned integers | 2 bytes |
int32, uint32 | 32-bit signed and unsigned integers | 4 bytes |
int64, uint64 | 64-bit signed and unsigned integers | 8 bytes |
float32 | 32-bit floating point number | 4 bytes |
float64 | 64-bit floating point number | 8 bytes |
complex64 | Complex number with 32-bit real and imaginary parts | 8 bytes |
complex128 | Complex number with 64-bit real and imaginary parts | 16 bytes |
byte | Similar to uint8 | 1 byte |
rune | Similar to int32, representing a Unicode code point | 4 bytes |
string | String type | Depends on the length of the string |
error | Error interface, used to return error information | No fixed size |
These types can be chosen according to different needs, such as numerical calculations, text processing, or logical control.
2 Integer Data Types
2.1 Overview of Integer Types
Go language has multiple built-in integer types, classified as follows:
- Signed integers:
int8
,int16
,int32
(orrune
),int64
, andint
- Unsigned integers:
uint8
(orbyte
),uint16
,uint32
,uint64
, anduint
The sizes of int
and uint
are 4 bytes on 32-bit systems and 8 bytes on 64-bit systems. The value ranges of integer data types are shown in the table below:
Type | Value Range |
---|---|
int8 | -128 to 127 |
uint8 | 0 to 255 |
int16 | -32768 to 32767 |
uint16 | 0 to 65535 |
int32 | -2147483648 to 2147483647 |
uint32 | 0 to 4294967295 |
int64 | -9223372036854775808 to 9223372036854775807 |
uint64 | 0 to 18446744073709551615 |
2.2 Using Integer Variables
The basic syntax for declaring an integer variable is as follows:
var variable_name data_type = initial_value
Sample code:
package main
import "fmt"
func main() {
var a int = 10 // Signed integer variable
var b uint = 20 // Unsigned integer variable
var c int8 = -128 // Smallest int8 value
fmt.Println(a, b, c)
}
2.3 Integer Operations
Go language supports common arithmetic operators, such as addition (+
), subtraction (-
), multiplication (*
), division (/
), and modulo (%
), as well as bitwise operators such as bitwise AND (&
), OR (|
), XOR (^
), left shift (<<
), and right shift (>>
).
package main
import "fmt"
func main() {
x := 10
y := 3
// Arithmetic operations
fmt.Println(x + y) // Addition
fmt.Println(x - y) // Subtraction
fmt.Println(x * y) // Multiplication
fmt.Println(x / y) // Division
fmt.Println(x % y) // Modulo
// Bitwise operations
fmt.Println(x & y) // Bitwise AND
fmt.Println(x | y) // Bitwise OR
fmt.Println(x ^ y) // Bitwise XOR
fmt.Println(x << 1) // Left shift by 1
fmt.Println(x >> 1) // Right shift by 1
}
3 Floating Point Data Types
3.1 Overview of Floating Point Data Types
In Go language, floating-point types include float32
and float64
, corresponding to 32-bit and 64-bit floating-point data. In general, it is recommended to use float64
because it provides a larger range and more accurate precision.
-
float32
has approximately 23 significant bits, providing about 7 decimal digits of precision. -
float64
has approximately 52 significant bits, providing about 16 decimal digits of precision.
3.2 Using Floating Point Variables
Floating-point variables can be declared by directly providing literals or using the var
keyword:
package main
import "fmt"
func main() {
var f1 float32 = 3.14 // Explicitly specify float32 type
f2 := 3.14 // Automatically inferred as float64 type
fmt.Println(f1, f2)
}
3.3 Floating Point Arithmetic and Issues
Floating-point arithmetic may lead to precision loss. Performing operations with very high precision is a common problem, especially when subtracting two very close numbers.
package main
import "fmt"
func main() {
f1 := .1
f2 := .2
f3 := f1 + f2
fmt.Println(f3) // The output may not be the expected .3 due to precision issues
// Fixing precision issues using formatted output
fmt.Printf("%.1f\n", f3) // Output corrected to .3
}
4 Boolean Data Type
4.1 Overview of Boolean Data Type
Boolean is the simplest data type, and it can only have two values: true
(true) and false
(false). It holds a very important position in conditional statements and loop control structures.
4.2 Using Boolean Variables
Declaring and using boolean variables:
package main
import "fmt"
func main() {
var success bool = true
var fail bool = false
fmt.Println("Operation successful:", success)
fmt.Println("Operation failed:", fail)
}
Boolean values are often used in conditional statements:
package main
import "fmt"
func main() {
a := 10
b := 20
fmt.Println("a == b:", a == b) // false
fmt.Println("a < b:", a < b) // true
}
5 String Data Type
5.1 String Overview
A string is a collection of characters. In the Go language, strings are immutable. Each string consists of two parts: a pointer to the underlying byte array and a length. Strings can contain any data, including bytes.
5.2 Using String Variables
String variables are typically declared using double quotes "
to create, but you can also use backticks ` to create multi-line strings:
package main
import "fmt"
func main() {
var s1 string = "hello"
s2 := "world"
s3 := `This is a
multiple line
string`
fmt.Println(s1)
fmt.Println(s2)
fmt.Println(s3)
}
Once a string is created, its content cannot be changed. The following operation is illegal and will result in a compilation error:
s := "hello"
s[] = 'H` // Compilation error: string content is immutable
5.3 String Operations
Strings are very common and important in programming. The Go language provides a rich set of built-in functions for string manipulation. Here are some commonly used operations.
5.3.1 String Concatenation
In the Go language, you can use the plus sign (+
) operator to concatenate strings, which is the most straightforward method. Additionally, when dealing with frequent concatenation of multiple strings, it is recommended to use strings.Builder
for better performance.
package main
import (
"fmt"
"strings"
)
func main() {
// Concatenating strings using +
hello := "Hello, "
world := "World!"
result := hello + world
fmt.Println(result) // Output: Hello, World!
// Concatenating strings using strings.Builder
var sb strings.Builder
sb.WriteString("Hello, ")
sb.WriteString("World!")
fmt.Println(sb.String()) // Output: Hello, World!
}
5.3.2 String Splitting
String splitting can be done using the strings.Split
function, which splits the string into a slice based on the specified delimiter.
package main
import (
"fmt"
"strings"
)
func main() {
// Define a string
sentence := "Go is an open source programming language"
// Split the string by space
words := strings.Split(sentence, " ")
for _, word := range words {
fmt.Printf("%s\n", word)
}
// Output:
// Go
// is
// an
// open
// source
// programming
// language
}
5.3.3 Index Access
In Go, a string is an immutable sequence of bytes. You can use indexing to access specific bytes in a string. However, it's important to note that since a string may contain multi-byte characters (such as UTF-8 encoded characters), directly indexing may not yield the expected single character.
package main
import "fmt"
func main() {
s := "Hello, 世界"
for i := ; i < len(s); i++ {
fmt.Printf("%d: %x\n", i, s[i])
}
// Note: this will output the hexadecimal representation of bytes, not characters
}
To iterate through the string by character, you can use the range
loop.
package main
import "fmt"
func main() {
s := "Hello, 世界"
for index, runeValue := range s {
fmt.Printf("%d: %U '%c'\n", index, runeValue, runeValue)
}
// Output: index, Unicode encoding, and the character itself for each character
}
5.3.4 Getting the Length
The len
function can obtain the length of a string, that is, the length of the underlying byte sequence. For UTF-8 strings, if you need to obtain the number of characters (runes), you should use the utf8.RuneCountInString
function. This can correctly handle multi-byte characters.
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "Hello, 世界"
fmt.Println("Bytes length:", len(s)) // Output the byte length
fmt.Println("Runes length:", utf8.RuneCountInString(s)) // Output the character length
}
From the example above, we can see that Go language provides rich library functions for string operations, making it easy to accomplish various string processing tasks. When coding, it's important to pay attention to the distinction between bytes and characters, especially when dealing with non-ASCII character sets.