SoFunction
Updated on 2025-03-05

Detailed introduction to Go language data types

1. Two major data types of Go language

Go language data types include two categories: basic types and compound types.

Basic types include:

  • Boolean type bool.
  • Numeric types int,int8,int16,int32,int64,float32,float64.
  • uint8,uint16,uint32,uint64。
  • string string,byte,rune.

Compound types include:

  • Pointer, array, slice, dictionary, channel, structure, interface.

The following is annotated by code:

2. Basic Type

Declare a variable of type bool, with only two values: true and false, and the initial value is false

var isLogin bool
    
// Declare a variable of type int with the initial value of 0//(int8,int16,int32 uint8,uint16....similar, just the difference between signed and unsigned)// The most commonly used is int. If you need a larger range, you can use int64 or uint64.var count int
        
// Declare a variable of type string, with the initial value of ""var s string
        
//Declare a variable of type bytevar b byte
    
//Declare a rune type variable//The alias of int32 represent a single Unicode charactervar r rune

3. Compound type

pointer

The pointer of go and the pointer type of c language both represent the address of a variable. The difference is that the pointer of go is much simpler than the pointer of c. The old rules are used to code comments.as follows:

package main

import "fmt"

func main() {
    
    var count = 100 //Define the variable count    
    var ptr *int     //Define a pointer ptr, this pointer can save the address of an int type variable    ptr = &count    //ptr saves the address of the variable count, and the & symbol is the symbol of the variable address    
    ("count=",count) //Print the value of count    ("ptr=", *ptr)    //Print the value of the variable pointed to by ptr, this sentence prints 100}

The operation results are as follows:

count= 100
ptr= 100

4. Array

The array is a set of data of the same data type, with a fixed size and cannot be changed. Each element is called an element, and the default value of the declared array element is the 0 value of the corresponding type. Moreover, array is a value type in Go language (value type). All value type variables will have a copy action when assigning values ​​and passing them as parameters, that is, copying the original value.

package main

import "fmt"

func main() {
    
    // 1. Assign value after declaration (var <array name> [<array length>]<array element>)    var arr [2]int   // The default values ​​of array elements are 0    (arr) // Output: [0 0]    arr[0] = 1
    arr[1] = 2
    (arr) // Output: [1 2]    
    // 2. Declare and assign value (var <array name> = [<array length>]<array element>{element 1, element 2,...})    var intArr = [2]int{1, 2}
    strArr := [3]string{`aa`, `bb`, `cc`}
    (intArr) // Output: [1 2]    (strArr) // Output: [aa bb cc]    
    // 3. The size is not set during declaration. After assignment, the language itself will calculate the array size.    // var <array name> [<array length>]<array element> = [...]<element type>{element 1, element 2,...}    var arr1 = [...]int{1, 2}
    arr2 := [...]int{1, 2, 3}
    (arr1) // Output: [1 2]    (arr2) // Output: [1 2 3]    //arr1[2] = 3 // An error was reported in the compilation, the array size has been set to 2    
    // 4. The size is not set when declaring, and the index is specified when assigning values.    // var <array name> [<array length>]<array element> = [...]<element type>{index1:element1,index2:element2,...}    var arr3 = [...]int{1: 22, 0: 11, 2: 33}
    arr4 := [...]string{2: "cc", 1: "bb", 0: "aa"}
    (arr3) // Output: [11 22 33]    (arr4) // Output: [aa bb cc]    
    // traverse array    for i := 0; i &lt; len(arr4); i++ {
        v := arr4[i]
        ("i:%d, value:%s\n", i, v)
    }
}

5. Slice

Because the length of the array cannot be modified after definition, slices are needed to process variable-length array data. A slice can be regarded as a variable-length array, a reference type.

It contains three data:

  • Pointer to native array
  • Number of elements in a slice
  • Slice allocated storage space

Note:Students who understand C++ and Java can refer to vector and List. Slicing is similar to these two data structures, and directly enter the code:

package main

import "fmt"

func main() {
    var sl []int             // Declare a slice    sl = append(sl, 1, 2, 3) // Add value to the slice    (sl)          // Output: [1 2 3]
    var arr = [5]int{1, 2, 3, 4, 5} // Initialize an array    var sl1 = arr[0:2]              // Colon: The left is the start bit (including the start bit data), and the right is the end bit (not including the end bit data); if it is not filled, it is the head or tail by default    var sl2 = arr[3:]
    var sl3 = arr[:5]

    (sl1) // Output: [1 2]    (sl2) // Output: [4 5]    (sl3) // Output: [1 2 3 4 5]
    sl1 = append(sl1, 11, 22) // Add elements    (sl1)          // Output: [1 2 11 22]}

Use the make keyword to create slices directly.

grammar:make([] type, size, reserved space size), make() function is used to declare slice slices, map dictionary, channel channels.

as follows:

package main

import "fmt"

func main() {
    var s1 = make([]int, 5)          // Define slices with 5 elements    s2 := make([]int, 5, 10)         // Define a slice of 5 elements and reserve 10 elements for storage space (I don’t know what the use of reserving space?)    s3 := []string{`aa`, `bb`, `cc`} // Create and initialize an array slice containing 3 elements directly    
    (s1, len(s1)) // Output: [0 0 0 0 0] 5    (s2, len(s2)) // Output: [0 0 0 0 0] 5    (s3, len(s3)) // [aa bb cc] 3
    
    s1[1] = 1 // Declare or initialize data in size, you can specify assignment values    s1[4] = 4
    //s1[5] = 5 // Compile error, exceeding the definition size    s1 = append(s1, 5)       // Append elements    (s1, len(s1)) // Output: [0 1 0 0 4 5] 6    
    s2[1] = 1
    s2 = append(s2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
    (s2, len(s2)) // Output: [0 1 0 0 0 1 2 3 4 5 6 7 8 9 10 11] 16    
    // traverse slices    for i := 0; i &lt; len(s2); i++ {
        v := s2[i]
        ("i: %d, value:%d \n", i, v)
    }
}

6. Dictionary/map (map)

mapis an unordered set of key-value pairs, andslice Similar is also a reference type. The map itself is actually a pointer, pointing to a certain space in memory.

The declaration method is similar to that of an array, the declaration method is: var variable name map[key type value type or directly initialize with make function: make(map[key type] value type, initial space size).

The key value can be any value type that can be judged with ==, and the corresponding value type is not required.

Directly upload the code, as follows:

package main

import (
    "fmt"
    "unsafe"
)

func main() {
    // Assign value after declaration    var m map[int]string
    (m) // Output empty map: map[]    //m[1] = `aa`  // Assign value to an uninitialized map: panic: assignment to entry in nil map
    // Declare and initialize, use {} or make functions (create types and allocate space)    var m1 = map[string]int{}
    var m2 = make(map[string]int)
    m1[`a`] = 11
    m2[`b`] = 22
    (m1) // Output: map[a:11]    (m2) // Output: map[b:22]
    // Initialize multiple values    var m3 = map[string]string{"a": "aaa", "b": "bbb"}
    m3["c"] = "ccc"
    (m3) // Output: map[a:aaa b:bbb c:ccc]
    // Delete the value in the map    delete(m3, "a") // Delete the value corresponding to key a    (m3) // Output: map[b:bbb c:ccc]
    // Find elements in map    v, ok := m3["b"]
    if ok {
        (ok)
        ("The value of b in m3 is:", v) // Output: The value of b in m3 is: bbb    }
    // or    if v, ok := m3["b"]; ok { // The process is discussed later        ("The value of b in m3 is:", v) // Output: The value of b in m3 is: bbb    }

    (m3["c"]) // Directly take the value, output: ccc
    // The value in map can be of any type    m4 := make(map[string][5]int)
    m4["a"] = [5]int{1, 2, 3, 4, 5}
    m4["b"] = [5]int{11, 22, 33}
    (m4)                // Output: map[a:[1 2 3 4 5] b:[11 22 33 0 0]]    ((m4)) // Output: 8, 8 bytes, map is actually a pointer, pointing to a certain memory space}

7. Channel (channel)

Speaking of channelschannel, you must first understand the Go languagegoroutineCoroutines (lightweight threads). The channel provides a channel for communication between goroutines.goroutineIt is a language-level coroutine provided by Go, and is an encapsulation of CPU threads and schedulers.

channelIt is also type-dependent, and a channel can only pass values ​​of one type.

statement:var channel name chan channel passing value type or make function initialization: make (chan value type, initial storage space size)

To put it bluntly, the channel is similar to the message queue, and is mainly used in concurrent programming.

Directly upload the code, as follows:

package main

import (
    "fmt"
    "time"
)

func main() {
    var ch1 chan int            // Declare a channel    ch1 = make(chan int)        // Uninitialized channels cannot store data, initialize a channel    ch2 := make(chan string, 2) // Declare and initialize a channel with buffer space
    // Write data into the channel through anonymous function, and write to the <- method    go func() { ch1 &lt;- 1 }()
    go func() { ch2 &lt;- `a` }()

    v1 := &lt;-ch1 // Read data from the channel    v2 := &lt;-ch2
    (v1) // Output: 1    (v2) // Output: a
    // Write and read channel data    ch3 := make(chan int, 1) // Initialize a channel with buffer space    go readFromChannel(ch3)
    go writeToChannel(ch3)

    // The main thread sleeps for 1 second, and gives the execution permission to the child Go program, that is, the goroutine opened through go, otherwise the main program will end directly    (1 * )
}

func writeToChannel(ch chan int) {
    for i := 1; i &lt; 10; i++ {
        ("Write:", i)
        ch &lt;- i
    }
}

func readFromChannel(ch chan int) {
    for i := 1; i &lt; 10; i++ {
        v := &lt;-ch
        ("Read:", v)
    }
}

The operation results are as follows:

// ------ Output: -------
1
a
Write: 1
Write: 2
Write: 3
Read: 1
Read: 2
Read: 3
Write: 4
Write: 5
Write: 6
Read: 4
Read: 5
Read: 6
Write: 7
Write: 8
Write: 9
Read: 7
Read: 8
Read: 9

goroutine andchannelThe detailed usage of this chapter will be discussed in the corresponding blog specifically. For details, please find the relevant blog reference in my personal homepage.

8. Struct

A structure is an aggregated data type, an entity aggregated from zero or more values ​​of any type. Each value is called a member of the structure, and the class in java means the same as:

package main

import "fmt"

// Define a structure persontype person struct {
    name string
    age  int
}

func main() {
    var p person   // Declare a person type variable p     = "max" // Assignment     = 12
    (p) // Output: {max 12}
    p1 := person{name: "mike", age: 10} // Initialize a person directly    ()                // Output: mike
    p2 := new(person) // The new function allocates a pointer to the person type data     = `Zhang San`
     = 15
    (*p2) // Output: {Zhang San 15}}

9. Interface

Interfaces are used to define behavior. The Go language is different from object-oriented languages, without the concept of classes and no inheritance in the traditional sense. Interfaces in the Go language are used to define one or a group of behaviors. Some objects implement the behavior defined by the interface, and the type is the interface type.

Defining an interface also uses the type keyword, and the format is:

// Define an interfacetype InterfaceName interface {
    FuncName1(paramList) returnType
    FuncName2(paramList) returnType
    ...
}

Actual list:

package main

import (
    "fmt"
    "strconv"
)

// Define a Person interfacetype Person interface {
    Say(s string) string
    Walk(s string) string
}

// Define a Man structuretype Man struct {
    Name string
    Age  int
}

// Man implements Say methodfunc (m Man) Say(s string) string {
    return s + ", my name is " + 
}

// Man implements the Walk method, () to stringfunc (m Man) Walk(s string) string {
    return "Age: " + () + " and " + s
}

func main() {
    var m Man       // Declare a variable of type Man     = "Mike" // Assignment     = 30
    (("hello"))    // Output: hello, my name is Mike    (("go work")) // Output: Age: 30 and go work
    jack := Man{Name: "jack", Age: 25} // Initialize a Man type data    ()
    (("hi")) // Output: hi, my name is jack}

10. Error

The error type itself is an interface defined within the Go language. The interface defines a method for Error() to print error messages.The source code is as follows:

type error interface {
    Error() string
}

Custom error message:

package main

import (
    "errors"
    "fmt"
)

func main() {
    // Use errors to customize error messages    var e error
    e = ("This is a test error")
    (()) // Output: This is a test error
    // Use () to customize error messages    err := ("This is another error")
    (err) // Output: This is another test error}

This is the end of this article about the detailed introduction of Go language data types. For more relevant Go data types, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!