Day 7: Understanding Arrays and Slices in Go

Venkat Annangi
Venkat Annangi
23/09/2024 15:54 2 min read 40 views
#golang #108 days of golang

<h2>Day 7: Understanding Arrays and Slices in Go</h2>

<p>Go provides arrays and slices for working with collections of data. Today, we’ll explore how to declare, initialize, and manipulate arrays and slices, and why slices are preferred in most cases.</p>

<h3>Step 1: Arrays</h3>
<p>Arrays in Go are fixed-size collections of elements of the same type:</p>
<pre><code>var numbers [5]int
numbers[0] = 10
fmt.Println(numbers)
</code></pre>

<p>Arrays are rarely used directly because their size is fixed at the time of creation. Instead, Go encourages the use of slices.</p>

<h3>Step 2: Slices</h3>
<p>Slices are more flexible than arrays and can dynamically resize. You can create a slice from an array or use the <code>make()</code> function:</p>
<pre><code>nums := []int{1, 2, 3, 4, 5}
fmt.Println(nums)
</code></pre>

<h3>Step 3: Slice Operations</h3>
<p>Go provides several built-in functions for working with slices:</p>
<ul>
   <li><code>len(slice)</code> - returns the length of the slice</li>
   <li><code>append(slice, value)</code> - appends a value to the end of the slice</li>
   <li><code>copy(dest, src)</code> - copies elements from one slice to another</li>
</ul>

<p>Example of appending to a slice:</p>
<pre><code>nums := []int{1, 2, 3}
nums = append(nums, 4, 5)
fmt.Println(nums)  // Output: [1 2 3 4 5]
</code></pre>

<h3>Practical Exercise</h3>
<p>Write a Go program that takes an array of integers, creates a slice from it, and appends new values to the slice. Print both the original array and the modified slice:</p>
<pre><code>package main

import "fmt"

func main() {
   arr := [3]int{1, 2, 3}
   slice := arr[:]
   slice = append(slice, 4, 5)
   fmt.Println("Array:", arr)
   fmt.Println("Slice:", slice)
}
</code></pre>
 

Comments