Category: Go

  • Error Handling

    Go programming provides a pretty simple error handling framework with inbuilt error interface type of the following declaration −

    type error interface {
       Error() string
    }
    

    Functions normally return error as last return value. Use errors.New to construct a basic error message as following −

    func Sqrt(value float64)(float64, error) {
       if(value < 0){
    
      return 0, errors.New("Math: negative number passed to Sqrt")
    } return math.Sqrt(value), nil }

    Use return value and error message.

    result, err:= Sqrt(-1)
    
    if err != nil {
       fmt.Println(err)
    }

    Example

    Live Demo

    package main
    
    import "errors"
    import "fmt"
    import "math"
    
    func Sqrt(value float64)(float64, error) {
       if(value < 0){
    
      return 0, errors.New("Math: negative number passed to Sqrt")
    } return math.Sqrt(value), nil } func main() { result, err:= Sqrt(-1) if err != nil {
      fmt.Println(err)
    } else {
      fmt.Println(result)
    } result, err = Sqrt(9) if err != nil {
      fmt.Println(err)
    } else {
      fmt.Println(result)
    } }

    When the above code is compiled and executed, it produces the following result −

    Math: negative number passed to Sqrt
    3
    
  • Interfaces

    Go programming provides another data type called interfaces which represents a set of method signatures. The struct data type implements these interfaces to have method definitions for the method signature of the interfaces.

    Syntax

    /* define an interface */
    type interface_name interface {
       method_name1 [return_type]
       method_name2 [return_type]
       method_name3 [return_type]
       ...
       method_namen [return_type]
    }
    
    /* define a struct */
    type struct_name struct {
       /* variables */
    }
    
    /* implement interface methods*/
    func (struct_name_variable struct_name) method_name1() [return_type] {
       /* method implementation */
    }
    ...
    func (struct_name_variable struct_name) method_namen() [return_type] {
       /* method implementation */
    }
    

    Example

    Live Demo

    package main
    
    import ("fmt" "math")
    
    /* define an interface */
    type Shape interface {
       area() float64
    }
    
    /* define a circle */
    type Circle struct {
       x,y,radius float64
    }
    
    /* define a rectangle */
    type Rectangle struct {
       width, height float64
    }
    
    /* define a method for circle (implementation of Shape.area())*/
    func(circle Circle) area() float64 {
       return math.Pi * circle.radius * circle.radius
    }
    
    /* define a method for rectangle (implementation of Shape.area())*/
    func(rect Rectangle) area() float64 {
       return rect.width * rect.height
    }
    
    /* define a method for shape */
    func getArea(shape Shape) float64 {
       return shape.area()
    }
    
    func main() {
       circle := Circle{x:0,y:0,radius:5}
       rectangle := Rectangle {width:10, height:5}
       
       fmt.Printf("Circle area: %f\n",getArea(circle))
       fmt.Printf("Rectangle area: %f\n",getArea(rectangle))
    }

    When the above code is compiled and executed, it produces the following result −

    Circle area: 78.539816
    Rectangle area: 50.000000
    
  • Recursion

    Recursion is the process of repeating items in a self-similar way. The same concept applies in programming languages as well. If a program allows to call a function inside the same function, then it is called a recursive function call. Take a look at the following example −

    func recursion() {
       recursion() /* function calls itself */
    }
    func main() {
       recursion()
    }

    The Go programming language supports recursion. That is, it allows a function to call itself. But while using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go on to become an infinite loop.

    Examples of Recursion in Go

    Recursive functions are very useful to solve many mathematical problems such as calculating factorial of a number, generating a Fibonacci series, etc.

    Example 1: Calculating Factorial Using Recursion in Go

    The following example calculates the factorial of a given number using a recursive function −

    package main
    
    import "fmt"
    
    func factorial(i int)int {
       if(i <= 1) {
    
      return 1
    } return i * factorial(i - 1) } func main() { var i int = 15 fmt.Printf("Factorial of %d is %d", i, factorial(i)) }

    When the above code is compiled and executed, it produces the following result −

    Factorial of 15 is 1307674368000
    

    Example 2: Fibonacci Series Using Recursion in Go

    The following example shows how to generate a Fibonacci series of a given number using a recursive function

    package main
    
    import "fmt"
    
    func fibonaci(i int) (ret int) {
       if i == 0 {
    
      return 0
    } if i == 1 {
      return 1
    } return fibonaci(i-1) + fibonaci(i-2) } func main() { var i int for i = 0; i < 10; i++ {
      fmt.Printf("%d ", fibonaci(i))
    } }

    When the above code is compiled and executed, it produces the following result −

    0 1 1 2 3 5 8 13 21 34 
    
  • Maps

    Go provides another important data type named map which maps unique keys to values. A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key.

    Defining a Map

    You must use make function to create a map.

    /* declare a variable, by default map will be nil*/
    var map_variable map[key_data_type]value_data_type
    
    /* define the map as nil map can not be assigned any value*/
    map_variable = make(map[key_data_type]value_data_type)
    

    Example

    The following example illustrates how to create and use a map −

    package main
    
    import "fmt"
    
    func main() {
       var countryCapitalMap map[string]string
       /* create a map*/
       countryCapitalMap = make(map[string]string)
       
       /* insert key-value pairs in the map*/
       countryCapitalMap["France"] = "Paris"
       countryCapitalMap["Italy"] = "Rome"
       countryCapitalMap["Japan"] = "Tokyo"
       countryCapitalMap["India"] = "New Delhi"
       
       /* print map using keys*/
       for country := range countryCapitalMap {
    
      fmt.Println("Capital of",country,"is",countryCapitalMap&#91;country])
    } /* test if entry is present in the map or not*/ capital, ok := countryCapitalMap["United States"] /* if ok is true, entry is present otherwise entry is absent*/ if(ok){
      fmt.Println("Capital of United States is", capital)  
    } else {
      fmt.Println("Capital of United States is not present") 
    } }

    When the above code is compiled and executed, it produces the following result −

    Capital of India is New Delhi
    Capital of France is Paris
    Capital of Italy is Rome
    Capital of Japan is Tokyo
    Capital of United States is not present
    

    delete() Function

    delete() function is used to delete an entry from a map. It requires the map and the corresponding key which is to be deleted. For example −

    package main
    
    import "fmt"
    
    func main() {   
       /* create a map*/
       countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo","India":"New Delhi"}
       
       fmt.Println("Original map")   
       
       /* print map */
       for country := range countryCapitalMap {
    
      fmt.Println("Capital of",country,"is",countryCapitalMap&#91;country])
    } /* delete an entry */ delete(countryCapitalMap,"France"); fmt.Println("Entry for France is deleted") fmt.Println("Updated map") /* print map */ for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap&#91;country])
    } }

    When the above code is compiled and executed, it produces the following result −

    Original Map
    Capital of France is Paris
    Capital of Italy is Rome
    Capital of Japan is Tokyo
    Capital of India is New Delhi
    Entry for France is deleted
    Updated Map
    Capital of India is New Delhi
    Capital of Italy is Rome
    Capital of Japan is Tokyo
    
  • Range

    The range keyword is used in for loop to iterate over items of an array, slice, channel or map. With array and slices, it returns the index of the item as integer. With maps, it returns the key of the next key-value pair. Range either returns one value or two. If only one value is used on the left of a range expression, it is the 1st value in the following table.

    Range expression1st Value2nd Value(Optional)
    Array or slice a [n]Eindex i inta[i] E
    String s string typeindex i intrune int
    map m map[K]Vkey k Kvalue m[k] V
    channel c chan Eelement e Enone

    Example

    The following paragraph shows how to use range −

    package main
    
    import "fmt"
    
    func main() {
       /* create a slice */
       numbers := []int{0,1,2,3,4,5,6,7,8} 
       
       /* print the numbers */
       for i:= range numbers {
    
      fmt.Println("Slice item",i,"is",numbers&#91;i])
    } /* create a map*/ countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo"} /* print map using keys*/ for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap&#91;country])
    } /* print map using key-value*/ for country,capital := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",capital)
    } }

    When the above code is compiled and executed, it produces the following result −

    Slice item 0 is 0
    Slice item 1 is 1
    Slice item 2 is 2
    Slice item 3 is 3
    Slice item 4 is 4
    Slice item 5 is 5
    Slice item 6 is 6
    Slice item 7 is 7
    Slice item 8 is 8
    Capital of France is Paris
    Capital of Italy is Rome
    Capital of Japan is Tokyo
    Capital of France is Paris
    Capital of Italy is Rome
    Capital of Japan is Tokyo
    
  • Structures

    Go arrays allow you to define variables that can hold several data items of the same kind. Structure is another user-defined data type available in Go programming, which allows you to combine data items of different kinds.

    Structures are used to represent a record. Suppose you want to keep track of the books in a library. You might want to track the following attributes of each book −

    • Title
    • Author
    • Subject
    • Book ID

    In such a scenario, structures are highly useful.

    Defining a Structure

    To define a structure, you must use type and struct statements. The struct statement defines a new data type, with multiple members for your program. The type statement binds a name with the type which is struct in our case. The format of the struct statement is as follows −

    type struct_variable_type struct {
       member definition;
       member definition;
       ...
       member definition;
    }

    Once a structure type is defined, it can be used to declare variables of that type using the following syntax.

    variable_name := structure_variable_type {value1, value2...valuen}
    

    Accessing Structure Members

    To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. The following example explains how to use a structure −

    package main
    
    import "fmt"
    
    type Books struct {
       title string
       author string
       subject string
       book_id int
    }
    func main() {
       var Book1 Books    /* Declare Book1 of type Book */
       var Book2 Books    /* Declare Book2 of type Book */
     
       /* book 1 specification */
       Book1.title = "Go Programming"
       Book1.author = "Mahesh Kumar"
       Book1.subject = "Go Programming Tutorial"
       Book1.book_id = 6495407
    
       /* book 2 specification */
       Book2.title = "Telecom Billing"
       Book2.author = "Zara Ali"
       Book2.subject = "Telecom Billing Tutorial"
       Book2.book_id = 6495700
     
       /* print Book1 info */
       fmt.Printf( "Book 1 title : %s\n", Book1.title)
       fmt.Printf( "Book 1 author : %s\n", Book1.author)
       fmt.Printf( "Book 1 subject : %s\n", Book1.subject)
       fmt.Printf( "Book 1 book_id : %d\n", Book1.book_id)
    
       /* print Book2 info */
       fmt.Printf( "Book 2 title : %s\n", Book2.title)
       fmt.Printf( "Book 2 author : %s\n", Book2.author)
       fmt.Printf( "Book 2 subject : %s\n", Book2.subject)
       fmt.Printf( "Book 2 book_id : %d\n", Book2.book_id)
    }

    When the above code is compiled and executed, it produces the following result −

    Book 1 title      : Go Programming
    Book 1 author     : Mahesh Kumar
    Book 1 subject    : Go Programming Tutorial
    Book 1 book_id    : 6495407
    Book 2 title      : Telecom Billing
    Book 2 author     : Zara Ali
    Book 2 subject    : Telecom Billing Tutorial
    Book 2 book_id    : 6495700
    

    Structures as Function Arguments

    You can pass a structure as a function argument in very similar way as you pass any other variable or pointer. You would access structure variables in the same way as you did in the above example −

    package main
    
    import "fmt"
    
    type Books struct {
       title string
       author string
       subject string
       book_id int
    }
    func main() {
       var Book1 Books    /* Declare Book1 of type Book */
       var Book2 Books    /* Declare Book2 of type Book */
     
       /* book 1 specification */
       Book1.title = "Go Programming"
       Book1.author = "Mahesh Kumar"
       Book1.subject = "Go Programming Tutorial"
       Book1.book_id = 6495407
    
       /* book 2 specification */
       Book2.title = "Telecom Billing"
       Book2.author = "Zara Ali"
       Book2.subject = "Telecom Billing Tutorial"
       Book2.book_id = 6495700
     
       /* print Book1 info */
       printBook(Book1)
    
       /* print Book2 info */
       printBook(Book2)
    }
    func printBook( book Books ) {
       fmt.Printf( "Book title : %s\n", book.title);
       fmt.Printf( "Book author : %s\n", book.author);
       fmt.Printf( "Book subject : %s\n", book.subject);
       fmt.Printf( "Book book_id : %d\n", book.book_id);
    }

    When the above code is compiled and executed, it produces the following result −

    Book title     : Go Programming
    Book author    : Mahesh Kumar
    Book subject   : Go Programming Tutorial
    Book book_id   : 6495407
    Book title     : Telecom Billing
    Book author    : Zara Ali
    Book subject   : Telecom Billing Tutorial
    Book book_id   : 6495700
    

    Pointers to Structures

    You can define pointers to structures in the same way as you define pointer to any other variable as follows −

    var struct_pointer *Books
    

    Now, you can store the address of a structure variable in the above defined pointer variable. To find the address of a structure variable, place the & operator before the structure’s name as follows −

    struct_pointer = &Book1;
    

    To access the members of a structure using a pointer to that structure, you must use the “.” operator as follows −

    struct_pointer.title;
    

    Let us re-write the above example using structure pointer −

    package main
    
    import "fmt"
    
    type Books struct {
       title string
       author string
       subject string
       book_id int
    }
    func main() {
       var Book1 Books   /* Declare Book1 of type Book */
       var Book2 Books   /* Declare Book2 of type Book */
     
       /* book 1 specification */
       Book1.title = "Go Programming"
       Book1.author = "Mahesh Kumar"
       Book1.subject = "Go Programming Tutorial"
       Book1.book_id = 6495407
    
       /* book 2 specification */
       Book2.title = "Telecom Billing"
       Book2.author = "Zara Ali"
       Book2.subject = "Telecom Billing Tutorial"
       Book2.book_id = 6495700
     
       /* print Book1 info */
       printBook(&Book1)
    
       /* print Book2 info */
       printBook(&Book2)
    }
    func printBook( book *Books ) {
       fmt.Printf( "Book title : %s\n", book.title);
       fmt.Printf( "Book author : %s\n", book.author);
       fmt.Printf( "Book subject : %s\n", book.subject);
       fmt.Printf( "Book book_id : %d\n", book.book_id);
    }

    When the above code is compiled and executed, it produces the following result −

    Book title     : Go Programming
    Book author    : Mahesh Kumar
    Book subject   : Go Programming Tutorial
    Book book_id   : 6495407
    Book title     : Telecom Billing
    Book author    : Zara Ali
    Book subject   : Telecom Billing Tutorial
    Book book_id   : 6495700
    
  • Pointers

    Pointers in Go are easy and fun to learn. Some Go programming tasks are performed more easily with pointers, and other tasks, such as call by reference, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect Go programmer.

    As you know, every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the following example, which will print the address of the variables defined −

    package main
    
    import "fmt"
    
    func main() {
       var a int = 10   
       fmt.Printf("Address of a variable: %x\n", &a  )
    }

    When the above code is compiled and executed, it produces the following result −

    Address of a variable: 10328000
    

    So you understood what is memory address and how to access it. Now let us see what pointers are.

    What Are Pointers?

    pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address. The general form of a pointer variable declaration is −

    var var_name *var-type
    

    Here, type is the pointer’s base type; it must be a valid C data type and var-name is the name of the pointer variable. The asterisk * you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration −

    var ip *int        /* pointer to an integer */
    var fp *float32    /* pointer to a float */
    

    The actual data type of the value of all pointers, whether integer, float, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.

    How to Use Pointers?

    There are a few important operations, which we frequently perform with pointers: (a) we define pointer variables, (b) assign the address of a variable to a pointer, and (c) access the value at the address stored in the pointer variable.

    All these operations are carried out using the unary operator * that returns the value of the variable located at the address specified by its operand. The following example demonstrates how to perform these operations −

    Live Demo

    package main
    
    import "fmt"
    
    func main() {
       var a int = 20   /* actual variable declaration */
       var ip *int      /* pointer variable declaration */
    
       ip = &a  /* store address of a in pointer variable*/
    
       fmt.Printf("Address of a variable: %x\n", &a  )
    
       /* address stored in pointer variable */
       fmt.Printf("Address stored in ip variable: %x\n", ip )
    
       /* access the value using the pointer */
       fmt.Printf("Value of *ip variable: %d\n", *ip )
    }

    When the above code is compiled and executed, it produces the following result −

    Address of var variable: 10328000
    Address stored in ip variable: 10328000
    Value of *ip variable: 20
    

    Nil Pointers in Go

    Go compiler assign a Nil value to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned nil is called a nil pointer.

    The nil pointer is a constant with a value of zero defined in several standard libraries. Consider the following program −

    package main
    
    import "fmt"
    
    func main() {
       var  ptr *int
    
       fmt.Printf("The value of ptr is : %x\n", ptr  )
    }

    When the above code is compiled and executed, it produces the following result −

    The value of ptr is 0
    

    On most of the operating systems, programs are not permitted to access memory at address 0 because that memory is reserved by the operating system. However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer contains the nil (zero) value, it is assumed to point to nothing.

    To check for a nil pointer you can use an if statement as follows −

    if(ptr != nil)     /* succeeds if p is not nil */
    if(ptr == nil)    /* succeeds if p is null */
    

    Go Pointers in Detail

    Pointers have many but easy concepts and they are very important to Go programming. The following concepts of pointers should be clear to a Go programmer −

    Sr.NoConcept & Description
    1Go – Array of pointersYou can define arrays to hold a number of pointers.
    2Go – Pointer to pointerGo allows you to have pointer on a pointer and so on.
    3Passing pointers to functions in GoPassing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function.
  • Arrays

    Go programming language provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

    Instead of declaring individual variables, such as number0, number1, …, and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and …, numbers[99] to represent individual variables. A specific element in an array is accessed by an index.

    All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

    Arrays in Go

    Declaring Arrays

    To declare an array in Go, a programmer specifies the type of the elements and the number of elements required by an array as follows −

    var variable_name [SIZE] variable_type
    

    This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid Go data type. For example, to declare a 10-element array called balance of type float32, use this statement −

    var balance [10] float32
    

    Here, balance is a variable array that can hold up to 10 float numbers.

    Initializing Arrays

    You can initialize array in Go either one by one or using a single statement as follows −

    var balance = [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0}
    

    The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ].

    If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −

    var balance = []float32{1000.0, 2.0, 3.4, 7.0, 50.0}
    

    You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array −

    balance[4] = 50.0
    

    The above statement assigns element number 5th in the array with a value of 50.0. All arrays have 0 as the index of their first element which is also called base index and last index of an array will be total size of the array minus 1. Following is the pictorial representation of the same array we discussed above −

    Array Presentation

    Accessing Array Elements

    An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −

    float32 salary = balance[9]
    

    The above statement will take 10th element from the array and assign the value to salary variable. Following is an example which will use all the above mentioned three concepts viz. declaration, assignment and accessing arrays −

    package main
    
    import "fmt"
    
    func main() {
       var n [10]int /* n is an array of 10 integers */
       var i,j int
    
       /* initialize elements of array n to 0 */         
       for i = 0; i < 10; i++ {
    
      n&#91;i] = i + 100 /* set element at location i to i + 100 */
    } /* output each array element's value */ for j = 0; j < 10; j++ {
      fmt.Printf("Element&#91;%d] = %d\n", j, n&#91;j] )
    } }

    When the above code is compiled and executed, it produces the following result −

    Element[0] = 100
    Element[1] = 101
    Element[2] = 102
    Element[3] = 103
    Element[4] = 104
    Element[5] = 105
    Element[6] = 106
    Element[7] = 107
    Element[8] = 108
    Element[9] = 109
    

    Go Arrays in Detail

    There are important concepts related to array which should be clear to a Go programmer −

    Sr.NoConcept & Description
    1Multi-dimensional arraysGo supports multidimensional arrays. The simplest form of a multidimensional array is the two-dimensional array.
    2Passing arrays to functionsYou can pass to the function a pointer to an array by specifying the array’s name without an index.
  • Scope Rules

    A scope in any programming is a region of the program where a defined variable can exist and beyond that the variable cannot be accessed. There are three places where variables can be declared in Go programming language −

    • Inside a function or a block (local variables)
    • Outside of all functions (global variables)
    • In the definition of function parameters (formal parameters)

    Let us find out what are local and global variables and what are formal parameters.

    Local Variables

    Variables that are declared inside a function or a block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. The following example uses local variables. Here all the variables a, b, and c are local to the main() function.

    Live Demo

    package main
    
    import "fmt"
    
    func main() {
       /* local variable declaration */
       var a, b, c int 
    
       /* actual initialization */
       a = 10
       b = 20
       c = a + b
    
       fmt.Printf ("value of a = %d, b = %d and c = %d\n", a, b, c)
    }

    When the above code is compiled and executed, it produces the following result −

    value of a = 10, b = 20 and c = 30
    

    Global Variables

    Global variables are defined outside of a function, usually on top of the program. Global variables hold their value throughout the lifetime of the program and they can be accessed inside any of the functions defined for the program.

    A global variable can be accessed by any function. That is, a global variable is available for use throughout the program after its declaration. The following example uses both global and local variables −

    Live Demo

    package main
    
    import "fmt"
     
    /* global variable declaration */
    var g int
     
    func main() {
       /* local variable declaration */
       var a, b int
    
       /* actual initialization */
       a = 10
       b = 20
       g = a + b
    
       fmt.Printf("value of a = %d, b = %d and g = %d\n", a, b, g)
    }

    When the above code is compiled and executed, it produces the following result −

    value of a = 10, b = 20 and g = 30
    

    A program can have the same name for local and global variables but the value of the local variable inside a function takes preference. For example −

    package main
    
    import "fmt"
     
    /* global variable declaration */
    var g int = 20
     
    func main() {
       /* local variable declaration */
       var g int = 10
     
       fmt.Printf ("value of g = %d\n",  g)
    }

    When the above code is compiled and executed, it produces the following result −

    value of g = 10
    

    Formal Parameters

    Formal parameters are treated as local variables with-in that function and they take preference over the global variables. For example −

    package main
    
    import "fmt"
     
    /* global variable declaration */
    var a int = 20;
     
    func main() {
       /* local variable declaration in main function */
       var a int = 10
       var b int = 20
       var c int = 0
    
       fmt.Printf("value of a in main() = %d\n",  a);
       c = sum( a, b);
       fmt.Printf("value of c in main() = %d\n",  c);
    }
    /* function to add two integers */
    func sum(a, b int) int {
       fmt.Printf("value of a in sum() = %d\n",  a);
       fmt.Printf("value of b in sum() = %d\n",  b);
    
       return a + b;
    }

    When the above code is compiled and executed, it produces the following result −

    value of a in main() = 10
    value of a in sum() = 10
    value of b in sum() = 20
    value of c in main() = 30
    

    Initializing Local and Global Variables

    Local and global variables are initialized to their default value, which is 0; while pointers are initialized to nil.

    Data TypeInitial Default Value
    int0
    float320
    pointernil
  • Loops

    There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.

    Programming languages provide various control structures that allow for more complicated execution paths.

    A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages −

    Loop Architecture

    Go programming language provides the following types of loop to handle looping requirements.

    Sr.NoLoop Type & Description
    1for loopIt executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
    2nested loopsThese are one or multiple loops inside any for loop.

    Loop Control Statements

    Loop control statements change an execution from its normal sequence. When an execution leaves its scope, all automatic objects that were created in that scope are destroyed.

    Go supports the following control statements −

    Sr.NoControl Statement & Description
    1break statementIt terminates a for loop or switch statement and transfers execution to the statement immediately following the for loop or switch.
    2continue statementIt causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
    3goto statementIt transfers control to the labeled statement.

    The Infinite Loop

    A loop becomes an infinite loop if its condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty or by passing true to it.

    package main
    
    import "fmt"
    
    func main() {
       for true  {
    
       fmt.Printf("This loop will run forever.\n");
    } }

    When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop.

    Note − You can terminate an infinite loop by pressing Ctrl + C keys.