Add Element to Slice
Lesson 3 of 21 in Coddy's Slices and Maps in Golang course.
In the last lessons, we discussed that the difference between a slice and an array lies in their size, which becomes evident when checking the length.
For instance, if we define a slice like this:
nums := []int{23, 5, 6}Our slice has three elements, and checking the length using the <strong>len()</strong> function gives us 3:
nums := []int{23, 5, 6}
fmt.Println(len(nums)) // 3If we add elements to the slice and check the size, we will get the new size:
nums := []int{23, 5, 6, 9, 22}
fmt.Println(len(nums)) // 5On the contrary, an array has a fixed size. For example:
nums := [4]int{23}
fmt.Println(len(nums)) // 4Even though it has fewer elements than 4, the length remains fixed.
Adding elements to a slice is done using <strong>append</strong>:
books := []string{"Python", "Rust"}
books = append(books, "Golang")
fmt.Println(books)Running this gives:
[Python Rust Golang]In Golang, slices come with built-in functions, and <strong>append()</strong> is one of them, enabling us to add new elements to an existing slice.
Note that, due to the dynamic size of slices, we cannot use the index to add elements (
<strong>books[2] = "Golang"</strong>won't work).
Challenge
EasyWrite a program that takes 3 inputs from the user and adds them to the slice named <strong>coddy</strong> as defined in the given code. Perform the following steps:
- Print the length of the slice before adding elements.
- Add elements to the slice.
- Print the slice and the updated length after adding elements (in different lines).
Try it yourself
package main
import "fmt"
func main() {
// Get the Input from the user Dont't change this!
var first, second, third string
fmt.Scan(&first)
fmt.Scan(&second)
fmt.Scan(&third)
// Define the Slice
coddy := []string {"SQL","Rust","C#","Golang"}
// Print the length
// Add element to the Slice
// Print the slice and the updated length
}All lessons in Slices and Maps in Golang
1Introduction
Introduction2Slices
Slices vs ArraysAdd Element to SliceSlicingSlicing WaysReslicingSlice CapacityMax CapacityIterate Over a SliceRecap Challenge #1