Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding Arrays and Slices in Go

Tech 2

Arrays and slice are distinct data structures in Go. Arrays have a fixed length, while slices are dynamic arrays that can grow or shrink in size.

To create an array:

fixedArray := [5]int{10, 20, 30, 40, 50}

// Using [...] syntax for automatic length determination
autoArray := [...]int{0, 1, 2, 3, 4, 5}

To create a slice:

// Empty brackets indicate a slice
slice1 := []int{1, 2, 3, 4, 5}

// Using make with specified length and capacity
slice2 := make([]int, 6, 8)

// Omitting capacity sets it equal to length
slice3 := make([]int, 6)

Converting an array to a slice involvse extracting a segment from the array and assigning it to a new variable of slice type.

Example:

func main() {
    numbers := [...]int{0, 1, 2, 3, 4, 5}

    segment := numbers[2:4]
    segment[0] += 100
    segment[1] += 200

    fmt.Println(segment)
    fmt.Println(numbers)
}
// Output:
// [102 203]
// [0 1 102 203 4 5]

Common methods to array-to-slice conversion:

  • slice := arr[:]
  • slice := data[2:4]
  • slice := arr[:5]

To convert an array to a slice and expand it:

package main

import "fmt"

func main() {
    originalArray := [5]int{1, 2, 3, 4, 5}
    
    convertedSlice := originalArray[:]
    
    additionalValue := 6
    
    convertedSlice = append(convertedSlice, additionalValue)
    
    fmt.Println(convertedSlice)
}

The fmt package provides formatted output functions like Printf, which uses format specifiers such as %T for type representation.

Advanced Go topics include goroutines for concurrency, channels for communication between goroutines, Go Modules for dependancy management, and ecosystem extensions like go-redis for Redis and GORM for ORM functionality.

Tags: go

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.