Professional Documents
Culture Documents
ACP Lecture 04 - Array and Slices
ACP Lecture 04 - Array and Slices
Lecture – 04
GO language Array and Slices
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
strArray1[0] = "Canada"
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
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"}
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
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
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
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…
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)
}