Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 28

Advance Computer Programming – GO

Lecture – 04
GO language Array and Slices

Instructor: Syed Mujtaba Hassan


Email: mujtaba.hassan@riphah.edu.pk
Session: Fall 2022
Riphah School of Computing and Innovation (RSCI)
Riphah International University, Lahore
Golang Arrays

An array is a data structure that consists of a collection of elements of a single


type or simply you can say a special variable, which can hold more than one value
at a time. The values an array holds are called its elements or items. An array holds
a specific number of elements, and it cannot grow or shrink. Different data types
can be handled as elements in arrays such as Int, String, Boolean, and others. The
index of the first element of any dimension of an array is 0, the index of the second
element of any array dimension is 1, and so on.
Declaring an Array

package main
import (
"fmt"
"reflect"
)
func main() {
var intArray [5]int
var strArray [5]string
fmt.Println(reflect.ValueOf(intArray).Kind())
fmt.Println(reflect.ValueOf(strArray).Kind())
}
What is reflect, var and literal in Golang?

Reflection gives you the ability to examine types at runtime. It also allows you to
examine, modify, and create variables, functions, and structs at runtime. Reflection
in Go is built around three concepts: Types, Kinds, and Values.

var keyword in Golang is used to create the variables of a particular type having a
proper name and initial value.

A literal of a value is a text representation of the value in code. A value may have
many literals. The literals denoting values of basic types are called basic value
literals.
Assign and Access Values
You access or assign the array elements by referring to the index number. The
index is specified in square brackets.
package main
import "fmt"
func main() {
var theArray [3]string
theArray[0] = “Lahore" // Assign a value to the first element
theArray[1] = “Islamabad" // Assign a value to the second element
theArray[2] = “Karachi" // Assign a value to the third element
fmt.Println(theArray[0]) // Access the first element value
fmt.Println(theArray[1]) // Access the second element value
fmt.Println(theArray[2]) // Access the third element value
}
Initializing an Array with an Array Literal

You can initialize an array with pre-defined values using an array literal. An array
literal have the number of elements it will hold in square brackets, followed by the
type of its elements. This is followed by a list of initial values separated by
commas of each element inside the curly braces.
package main
import "fmt"
func main() {
x := [5]int{10, 20, 30, 40, 50} // Intialized with values
var y [5]int = [5]int{10, 20, 30} // Partial assignment
fmt.Println(x)
fmt.Println(y)
}
Initializing an Array with ellipses...

When we use ... instead of specifying the length. The compiler can identify the
length of an array, based on the elements specified in the array declaration.

package main
import (
"fmt"
"reflect"
)
func main() {
x := [...]int{10, 20, 30}
fmt.Println(reflect.ValueOf(x).Kind())
fmt.Println(len(x))
}
Copy Array
You can create copy of an array, by assigning an array to a new variable either by value
or reference.

package main
import "fmt"
func main() {
strArray1 := [3]string{“Islamabad", “Lahore", “Karachi"}
strArray2 := strArray1 // data is passed by value
strArray3 := &strArray1 // data is passed by reference

fmt.Printf("strArray1: %v\n", strArray1)


fmt.Printf("strArray2: %v\n", strArray2)

strArray1[0] = "Canada"

fmt.Printf("strArray1: %v\n", strArray1)


fmt.Printf("strArray2: %v\n", strArray2)
fmt.Printf("*strArray3: %v\n", *strArray3)
}
Multidimensional Arrays in Go
Go programming language allows multidimensional arrays. Here is the general
form of a multidimensional array declaration.

var variable_name [SIZE1][SIZE2]...[SIZEN] variable_type


Two-Dimensional Arrays
A two-dimensional array is the simplest form of a multidimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-
dimensional integer array of size [x, y], you would write something as follows.

var arrayName [ x ][ y ] variable_type


Initializing Two-Dimensional Arrays

a = [3][4]int{
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
}
Golang Slices

A slice is a flexible and extensible data structure to implement and manage


collections of data. Slices are made up of multiple elements, all of the same type. A
slice is a segment of dynamic arrays that can grow and shrink as you see fit. Like
arrays, slices are index-able and have a length. Slices have a capacity and length
property.
Create Empty Slice

To declare the type for a variable that holds a slice, use an empty pair of square
brackets, followed by the type of elements the slice will hold.
package main
import (
"fmt"
"reflect"
)
func main() {
var intSlice []int
var strSlice []string
fmt.Println(reflect.ValueOf(intSlice).Kind())
fmt.Println(reflect.ValueOf(strSlice).Kind())
}
Declare Slice using Make
Slice can be created using the built-in function make. When you use make, one
option you have is to specify the length of the slice. When you just specify the
length, the capacity of the slice is the same.

package main
import (
"fmt"
"reflect"
)
func main() {
var intSlice = make([]int, 10) // when length and capacity is same
var strSlice = make([]string, 10, 20) // when length and capacity is different
fmt.Printf("intSlice \tLen: %v \tCap: %v\n", len(intSlice), cap(intSlice))
fmt.Println(reflect.ValueOf(intSlice).Kind())
fmt.Printf("strSlice \tLen: %v \tCap: %v\n", len(strSlice), cap(strSlice))
fmt.Println(reflect.ValueOf(strSlice).Kind())
}
Initialize Slice with values using a Slice Literal

A slice literal contain empty brackets followed by the type of elements the slice will
hold, and a list of the initial values each element will have in curly braces.

package main
import "fmt"

func main() {
var intSlice = []int{10, 20, 30, 40}
var strSlice = []string{“Islamabad", “Lahore", “Sahiwal"}

fmt.Printf("intSlice \tLen: %v \tCap: %v\n", len(intSlice), cap(intSlice))


fmt.Printf("strSlice \tLen: %v \tCap: %v\n", len(strSlice), cap(strSlice))
}
Declare Slice using new Keyword

A slice can be declare using new keyword followed by capacity in square brackets
then type of elements the slice will hold.

package main
import (
"fmt"
"reflect"
)
func main() {
var intSlice = new([50]int)[0:10]
fmt.Println(reflect.ValueOf(intSlice).Kind())
fmt.Printf("intSlice \tLen: %v \tCap: %v\n", len(intSlice), cap(intSlice))
fmt.Println(intSlice)
}
Add Items
To add an item to the end of the slice, use the append() method.

package main
import "fmt"
func main() {
a := make([]int, 2, 5)
a[0] = 10
a[1] = 20
fmt.Println("Slice A:", a)
fmt.Printf("Length is %d Capacity is %d\n", len(a), cap(a))
a = append(a, 30, 40, 50, 60, 70, 80, 90)
fmt.Println("Slice A after appending data:", a)
fmt.Printf("Length is %d Capacity is %d\n", len(a), cap(a))
}
Access Items

You access the slice items by referring to the index number.

package main
import "fmt"
func main() {
var intSlice = []int{10, 20, 30, 40}
fmt.Println(intSlice[0])
fmt.Println(intSlice[1])
fmt.Println(intSlice[0:3])
}
Change Item Value

To change the value of a specific item, refer to the index number.

package main
import "fmt"
func main() {
var strSlice = []string{“Lahore", “Sahiwal", “Islamabd"}
fmt.Println(strSlice)
strSlice[2] = “Lahore"
fmt.Println(strSlice)
}
Remove Item from Slice
RemoveIndex function created to remove specific item from String slice.

package main
import "fmt"
func main() {
var strSlice = []string{“Lahore", “Islamabad", “Sahiwal", “Okara", “Cantt"}
fmt.Println(strSlice)
strSlice = RemoveIndex(strSlice, 3)
fmt.Println(strSlice)
}
func RemoveIndex(s []string, index int) []string {
return append(s[:index], s[index+1:]...)
}
Copy a Slice
The built-in copy function is used to copy data from one slice to another.
package main
import "fmt"
func main() {
a := []int{5, 6, 7} // Create a smaller slice
fmt.Printf("[Slice:A] Length is %d Capacity is %d\n", len(a), cap(a))
b := make([]int, 5, 10) // Create a bigger slice
copy(b, a) // Copy function
fmt.Printf("[Slice:B] Length is %d Capacity is %d\n", len(b), cap(b))
fmt.Println("Slice B after copying:", b)
b[3] = 8
b[4] = 9
fmt.Println("Slice B after adding elements:", b)
}
Loop Through a Slice
You can loop through the list items by using a for loop.

package main
import "fmt"
func main() {
var strSlice = []string{“ISB", “LHR", “OKR", “SWL", “FSD"}
fmt.Println("\n---------------Example 1 --------------------\n")
for index, element := range strSlice {
fmt.Println(index, "--", element)
}
fmt.Println("\n---------------Example 2 --------------------\n")
for _, value := range strSlice {
fmt.Println(value)
}
Byte Slices

A byte is an 8-bit unsigned int. In Go we often use byte slices. And the "bytes"
package provides helper methods for byte slices (similar to strings).
We use methods, like append(), to build byte slices. We can specify them with
string literals. Methods like bytes. Index help us test and change bytes.
Byte slices

This program introduces byte slices. We create a byte slice from a string literal
"abc." We append a byte to a byte slice.String For clearer display, we convert a
byte slice into string with the string() built-in method.
Len A byte slice has a length, which we retrieve with len. And we can access
individual bytes.
Golang program that introduces byte slices
package main
import "fmt"
func main() {
values := []byte("abc")
fmt.Println(values)
// Append a byte.
values = append(values, byte('d'))
// Print string representation of bytes.
fmt.Println(string(values))
// Length of byte slice.
fmt.Println(len(values))
// First byte.
fmt.Println(values[0])
}
How to append anything (element, slice or string) to a slice

Append one slice to another


You can concatenate two slices using the three dots notation.
a := []int{1, 2}
b := []int{11, 22}
a = append(a, b...) // a == [1 2 11 22]
How to pass a Slice to Function in Golang?

Slice is a variable-length sequence which stores elements of a similar type, you are
not allowed to store different type of elements in the same slice. It is just like
an array having an index value and length, but the size of the slice is resized they
are not in fixed-size just like an array.

The slice is passed by value to a function along with the slice capacity, length, and
the pointer of the slice is always pointing to the underlying array.
So, if we made some change in the slice which is passed to the function by value
will reflect in the slice present outside the function.
In Go language, you are allowed to pass a slice to a function, means the function
gets the copy of the slice.
Continue…

Go program to illustrate how to pass a slice to the function


package main
import "fmt"
// Function in which slice
// is passed by value
func myfun(element []string) {
// Modifying the given slice
element[2] = "Java"
fmt.Println("Modified slice: ", element)
}
Continue…

func main() {
// Creating slice
slc := []string{"C#", "Python", "C", "Perl"}
fmt.Println("Initial slice: ", slc)
// Passing the slice to the function
myfun(slc)
fmt.Println("Final slice:", slc)
}

You might also like