Monday, April 27, 2015

Go Slice Functions - append and copy - Code Example

If you are new to Slices read the basics of slices here.

Go has two built-in functions to facilitate appending and copying with Slices:

1. append

As explained in the last article, unlike the fixed length arrays slices are dynamic in nature. append is a function that facilitate expansion of slices.

2. copy

copy function copies elements from a source to destination & returns the number of elements copied.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

import "fmt"

func main() {
 
     slice1 := []int{11,22,33,44,55}
     fmt.Println("Slice1 = ", slice1)
 
     slice2 := append(slice1, 66,77,88)
     fmt.Println("Slice2 = ", slice2)
 
     slice3 := append(slice1, 99)
     fmt.Println("Slice3 = ", slice3)
 
     slice4 := append(slice2, 99)
     fmt.Println("Slice4 = ", slice4)
 
     sliceWorkingDays := []string{"Mon", "Tue", "Wed", "Thu", "Fri"}
     sliceWeekDays := append(sliceWorkingDays, "Sat", "Sun")
     fmt.Println("Working Days = ", sliceWorkingDays )
     fmt.Println("Week Days = ", sliceWeekDays)
     fmt.Println("Weekends =", sliceWeekDays[5:])
}



Output


You can play with the above code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package main

import "fmt"

func main() {    
    slice1 := []int{1,2,3}     
    slice2 := make([]int, 3) // Change 3 to 1 and note the results
    slice3 := []int{2,4,6}
      
    copy(slice2, slice1)    
    fmt.Println("Slice1 = ", slice1, "| Slice2 = ", slice2) 
 
    copy(slice2, slice3)    
    fmt.Println("Slice1 = ", slice1, "| Slice2 = ", slice2, "| Slice3 = ", slice3) 
}


You can play with the above code here

Question

What is the output of below snippet?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package main

import "fmt"

func main() {    
    slice1 := []int{1,3,5,7}     
    slice2 := []int{2,4,6,8}
  
    fmt.Println("Slice1 = ", slice1, "| Slice2 = ", slice2) 
      
    copy(slice2, slice1[:])    
    fmt.Println("Slice1 = ", slice1, "| Slice2 = ", slice2)
}

Answer


Monday, April 20, 2015

Go Slices with Code Sample

If you are a newcomer, it is recommended that you read the previous post about Go - Arrays with Code Examples to fully understand Slices.

Slices?

Simple Arrays are fixed length and are not so flexible to use when it comes to practical programming scenarios. A Slice is a segment of an underlying array that can vary in length as per our requirement. In  plain English:




Slice = Variable length array  

Remember

  1. The length of a slice may be changed as long as it still fits within the limits of the underlying array.
  2. Slices are reference type - the variable are stored in the heap

Creating Slices

var studentAge []int

The above line of code declares a slice variable named studentAge. How's it different from a simple Array? Did you notice the missing length between the brackets? Yes, that's the only difference in terms of declaration. You can visit this post about Simple Go Arrays to see how we declared an Array.

Standard way to create a Slice is by using built-in make function:


studentAge := make([]int, 5)

The above statement creates a Slice with an initial length of 5 that is part of an underlying array of capacity  (maximum length) 5. 

A 3rd parameter which is optional can also be added to the make function:

studentAge := make([]int, 3, 5)

The above represents a Slice of length 3 that points to an underlying array of capacity (maximum length) 5. Graphically:

Following is shorthand version of assigning values to Slices 

studentAge := []int{12,15,11,13,10}


Changing the Length of a Slice - Reslicing

newAge := studentAge[0:2]

Here we are changing the length of studentAge slice. Where to start slicing and where to end slicing in the underlying array? (Note: underlying array has values {12,15,11,13,10}) 

                  0 is starting index from where we'll START slicing.
                  2 is the end index where we'll STOP slicing. [excluded - i.e. you must stop just before this index]

Try and execute the following code to fully understand what we mean by reslicing. Play here.

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import "fmt"

func main() {
    studentAge := []int{12,15,11,13,10}
    fmt.Println("Students Age ==", studentAge)
 
 //studentAge[0:1] means Slice at start_index 0 & end_index 1
 //If 'start_index' is not mentioned, by default it is 0
 //If 'end_index'  is not mentioned, by default it is the max length of underlying array
 
    fmt.Println(studentAge[0:1]) 
    fmt.Println(studentAge[0:2])
    fmt.Println(studentAge[1:2])
    fmt.Println(studentAge[1:3])
    fmt.Println(studentAge[0:0])
    fmt.Println(studentAge[0:])
    fmt.Println(studentAge[:3])
    fmt.Println(studentAge[:])
}

The output of the above snippet:
Hope the above makes sense. Please add your comment to let me know if I missed something in the description. Let us make these tutorials Go newcomer friendly. In the next post we'll learn about Adding Elements to a Slice.

Sunday, April 12, 2015

Go - Arrays with Code Examples

An array is a group of related data items (collection of similar items) that share a common name. 


Related data items = Items with same data type

Array Declaration
var studentName [3] string


The above variable named studentName represents an array of type string that can hold up to 3 student names.

var studentMarks [3] int

The above variable named studentMarks represents an array of type integers that can hold up to 3 integer values. Gaphically the declaration var studentMarks [3] int can be simplified as:

Assigning Values to Array


studentMarks[0] = 80
studentMarks[1] = 75
studentMarks[2] = 64


As we've specified the size (length) of the studentMarks variable to 3; it can't take more than 3 elements. Here it is important to note that Arrays are indexed starting from 0. So, studentMarks[0] = 80 is like telling the compiler to assign the value 80 to the 1st element of the array studentMarks. This can be graphically represented as:

Remember Go Arrays are value types i.e. if you assign one array to another you get a copy of the array because value type variables are created on the stack.

Code Examples


package main
import "fmt"
func main(){

 var studentMarks [3] int
 
 studentMarks[0] = 80
 studentMarks[1] = 75
 studentMarks[2] = 64
 
 //2nd element of the array
 fmt.Println(studentMarks[1])
 
 //All the elements of the array
 fmt.Println(studentMarks)
 
 //Lenth of the array 
 fmt.Println(len(studentMarks))
 
 //Calculate average marks 
 fmt.Println((studentMarks[0]+studentMarks[1]+studentMarks[2])/len(studentMarks))
}


The output of the above code is shown in the below image.
  • You can play & see the output of the above code at Go Playground
Now let us see how an experienced professional will write the Average Marks Calculation part of the above code:

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package main
import "fmt"
func main(){
  
     studentMarks := [3]int {80, 75, 64}  
     var totalMarks int
 
 //Calculate average marks
 
     for i := 0; i < len(studentMarks); i++ {  
     totalMarks += studentMarks[i]
 }
 
     fmt.Println(totalMarks/len(studentMarks))
}

  • You can play & see the output of the above code at Go Playground

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
package main
import "fmt"
func main(){
  
    studentMarks := [3]int {
     80, 
     75, 
     64, //Note the comma here in this line
   }  
   var totalMarks int
  
 /* Average marks using range keyword.
 Special FOR LOOP: A _ (underscore, known as blank identifier
 used below tells the compiler 
 that we don't need the iterator variable */
 
  for _, value := range studentMarks {    
 
  totalMarks += value
 }
 fmt.Println(totalMarks/len(studentMarks))
}



  • You can play & see the output of the above code at Go Playground
Question

What is the output of the following code?

1
2
3
4
5
6
7
8
package main
import "fmt"
func main(){

 var studentMarks [1] int 
 fmt.Println(studentMarks[0])
 
}

Take a guess.

Answer Clue

In Go, if we just declare a variable and do not initialize it, by default, Go assigns a zero value to the variable. Depending on the type:
  • An Integer variable is assigned 0, 
  • Boolean is assigned false, 
  • String is assigned with ""  i.e. empty space.

Practical Implementation

Arrays are a bit rigid as they are fixed length and can't grow dynamically in size. So, although there usage during practical programming is very limited the concept of Arrays must be understood to form a good foundation of what we're going to learn next i.e. Slices.

Feel free to comment and share.


Monday, April 6, 2015

Go SWITCH Statement with Code Examples

SWITCH is a Decision Making / Control Statement

Like many other popular languages, SWITCH Statement in Go is used when you have to select & execute one of many alternatives code blocks. This sounds similar to the use of long If...Else chains. Yes, but SWITCH Case comes in as a handy construct when the number of alternatives increases (say when you've got 4 or more alternatives).



  • In short SWITCH is better for code readability and in some cases may be a better choice (than If...Else) for performance gains.

This article contains 3 SWITCH code snippets on this page and another example linked here from a different page on this blog.

A Simple SWITCH Example


Switch Case Example
Output of the above code

You can play with the above code here at Playground

For programming beginners: Switch statement tests the value of a given expression (or variable) against a list of case vlues & when a match is found the statement block associated with that case is executed.

Another Example / Sample Code

Below is a sample code that finds out the country as output based on the user's selection from predefined list of cities. See the following code.




Based on the input given by the user you can see the output in the below image:




You can play around with the above code sample here.



Salient Points of SWITCH CASE

1. Default is optional.
2. case  statement can have multiple match expressions.
3. Switch cases evaluate cases from top to bottom, stopping when a case succeeds.
4. Like C# (and unlike Java, C & C++) a GO SWITCH case body breaks automatically, unless it ends with a fallthrough statement. [Point#3 & 4 are related]

What is fallthrough?


In the absence of the break statement in a case block, if the control moves to the next case block without any issue, it is known as fallthrough. See the following piece of code to understand fallthrough:


Note : See line# 15 of below code for fallthrough keyword.



fallthrough example

The output of above code is:


fallthrough output code
Fallthrough Explanation 

When you select anything between 0 to 5 (both inclusive) the code behaves as expected i.e. as the condition specified matches it prints the specific code block only and exits from the code block (i.e. SWITCH statement block). 



So, where's the catch? If you enter the digit 6 (as your lucky number) the code will not exit simply after printing six is your lucky number. It will go to the next statement also and execute it and that's what is shown in above image, marked within a red rectangle.

 
Hope you understood fallthrough.

Question

OK...then tell me what happens if you insert a fallthrough just after case 2 i.e. at line# 11 in the above image (Captioned: fallthrough example)?

It should print the following:


two is your lucky number

three is your lucky number

So, it simply means fallthrough will affect the next case only and NOT the entire block. Feel free to play with the code here.


Please spread the word if you think this post can help a beginner :-)