Blog

  • 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[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[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[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[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[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.

  • Decision Making

    Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

    Following is the general form of a typical decision making structure found in most of the programming languages −

    Decision making statements in Go

    Go programming language provides the following types of decision making statements. Click the following links to check their detail.

    Sr.NoStatement & Description
    1if statementAn if statement consists of a boolean expression followed by one or more statements.
    2if…else statementAn if statement can be followed by an optional else statement, which executes when the boolean expression is false.
    3nested if statementsYou can use one if or else if statement inside another if or else if statement(s).
    4switch statementA switch statement allows a variable to be tested for equality against a list of values.
    5select statementA select statement is similar to switch statement with difference that case statements refers to channel communications.
  • Functions

    Kotlin is a statically typed language, hence, functions play a great role in it. We are pretty familiar with function, as we are using function throughout our examples in our last chapters. A function is a block of code which is written to perform a particular task. Functions are supported by all the modern programming languages and they are also known as methods or subroutines.

    At a broad level, a function takes some input which is called parameters, perform certain actions on these inputs and finally returns a value.

    Kotlin Built-in Functions

    Kotlin provides a number of built-in functions, we have used a number of buil-in functions in our examples. For example print() and println() are the most commonly used built-in function which we use to print an output to the screen.

    Example

    funmain(args: Array<String>){println("Hello, World!")}

    User-Defined Functions

    Kotlin allows us to create our own function using the keyword fun. A user defined function takes one or more parameters, perform an action and return the result of that action as a value.

    Syntax

    funfunctionName(){// body of function }

    Once we defined a function, we can call it any number of times whenever it is needed. Following isa simple syntax to call a Kotlin function:

    functionName()

    Example

    Following is an example to define and call a user-defined function which will print simple “Hello, World!”:

    funmain(args: Array<String>){printHello()}funprintHello(){println("Hello, World!")}

    When you run the above Kotlin program, it will generate the following output:

    Hello, World!
    

    Function Parameters

    A user-defined function can take zero or more parameters. Parameters are options and can be used based on requirement. For example, our above defined function did not make use of any paramenter.

    Example

    Following is an example to write a user-defined function which will add two given numbers and print their sum:

    funmain(args: Array<String>){val a =10val b =20printSum(a, b)}funprintSum(a:Int, b:Int){println(a + b)}

    When you run the above Kotlin program, it will generate the following output:

    30
    

    Return Values

    A kotlin function return a value based on requirement. Again it is very much optional to return a value.

    To return a value, use the return keyword, and specify the return type after the function’s parantheses

    Example

    Following is an example to write a user-defined function which will add two given numbers and return the sum:

    funmain(args: Array<String>){val a =10val b =20val result =sumTwo(a, b)println( result )}funsumTwo(a:Int, b:Int):Int{val x = a + b
       
       return x
    }

    When you run the above Kotlin program, it will generate the following output:

    30
    

    Unit-returning Functions

    If a function does not return a useful value, its return type is Unit. Unit is a type with only one value which is Unit.

    funsumTwo(a:Int, b:Int):Unit{val x = a + b
       
       println( x )}

    The Unit return type declaration is also optional. The above code is equivalent to:

    funsumTwo(a:Int, b:Int){val x = a + b
       
       println( x )}

    Kotlin Recursive Function

    Recursion functions are useful in many scenerios like calculating factorial of a number or generating fibonacci series. Kotlin supports recursion which means a Kotlin function can call itself.

    Syntax

    funfunctionName(){...functionName()...}

    Example

    Following is a Kotlin program to calculate the factorial of number 10:

    funmain(args: Array<String>){val a =4val result =factorial(a)println( result )}funfactorial(a:Int):Int{val result:Int
       
       if( a <=1){
    
      result = a
    }else{
      result = a*factorial(a-1)}return result
    }

    When you run the above Kotlin program, it will generate the following output:

    24
    

    Kotlin Tail Recursion

    A recursive function is eligible for tail recursion if the function call to itself is the last operation it performs.

    Example

    Following is a Kotlin program to calculate the factorial of number 10 using tail recursion. Here we need to ensure that the multiplication is done before the recursive call, not after.

    funmain(args: Array<String>){val a =4val result =factorial(a)println( result )}funfactorial(a: Int, accum: Int =1): Int {val result = a * accum
    
    returnif(a &lt;=1){
        result
    }else{factorial(a -1, result)}}</code></pre>

    When you run the above Kotlin program, it will generate the following output:

    24
    

    Kotlin tail recursion is useful while calculating factorial or some other processing on large numbers. So to avoide java.lang.StackOverflowError, you must use tail recursion.

    Higher-Order Functions

    A higher-order function is a function that takes another function as parameter and/or returns a function.

    Example

    Following is a function which takes two integer parameters, a and b and additionally, it takes another function operation as a parameter:

    funmain(args: Array<String>){val result =calculate(4,5,::sum)println( result )}funsum(a: Int, b: Int)= a + b 
    
    funcalculate(a: Int, b: Int, operation:(Int, Int)-> Int): Int {returnoperation(a, b)}

    When you run the above Kotlin program, it will generate the following output:

    9
    

    Here we are calling the higher-order function passing in two integer values and the function argument ::sum. Here :: is the notation that references a function by name in Kotlin.

    Example

    Let's look one more example where a function returns another function. Here we defined a higher-order function that returns a function. Here (Int) -> Int represents the parameters and return type of the square function.

    funmain(args: Array<String>){val func =operation()println(func(4))}funsquare(x: Int)= x * x
    
    funoperation():(Int)-> Int {return::square                                       
    }

    When you run the above Kotlin program, it will generate the following output:

    9
    

    Kotlin Lambda Function

    Kotlin lambda is a function which has no name and defined with a curly braces {} which takes zero or more parameters and body of function.

    The body of function is written after variable (if any) followed by -> operator.

    Syntax

    {variable with type -> body of the function}

    Example

    funmain(args: Array<String>){val upperCase ={ str: String -> str.toUpperCase()}println(upperCase("hello, world!"))}

    When you run the above Kotlin program, it will generate the following output:

    HELLO, WORLD!
    

    Kotlin Inline Function

    An inline function is declared with inline keyword. The use of inline function enhances the performance of higher order function. The inline function tells the compiler to copy parameters and functions to the call site.

    Example

    funmain(args: Array<String>){myFunction({println("Inline function parameter")})}inlinefunmyFunction(function:()-> Unit){println("I am inline function - A")function()println("I am inline function - B")}

    When you run the above Kotlin program, it will generate the following output:

    I am inline function - A
    Inline function parameter
    I am inline function - B
    
  • Operators

    An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Go language is rich in built-in operators and provides the following types of operators −

    • Arithmetic Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Assignment Operators
    • Miscellaneous Operators

    This tutorial explains arithmetic, relational, logical, bitwise, assignment, and other operators one by one.

    Arithmetic Operators

    Following table shows all the arithmetic operators supported by Go language. Assume variable A holds 10 and variable B holds 20 then −

    Show Examples

    OperatorDescriptionExample
    +Adds two operandsA + B gives 30
    Subtracts second operand from the firstA – B gives -10
    *Multiplies both operandsA * B gives 200
    /Divides the numerator by the denominator.B / A gives 2
    %Modulus operator; gives the remainder after an integer division.B % A gives 0
    ++Increment operator. It increases the integer value by one.A++ gives 11
    Decrement operator. It decreases the integer value by one.A– gives 9

    Relational Operators

    The following table lists all the relational operators supported by Go language. Assume variable A holds 10 and variable B holds 20, then −

    Show Examples

    OperatorDescriptionExample
    ==It checks if the values of two operands are equal or not; if yes, the condition becomes true.(A == B) is not true.
    !=It checks if the values of two operands are equal or not; if the values are not equal, then the condition becomes true.(A != B) is true.
    >It checks if the value of left operand is greater than the value of right operand; if yes, the condition becomes true.(A > B) is not true.
    <It checks if the value of left operand is less than the value of the right operand; if yes, the condition becomes true.(A < B) is true.
    >=It checks if the value of the left operand is greater than or equal to the value of the right operand; if yes, the condition becomes true.(A >= B) is not true.
    <=It checks if the value of left operand is less than or equal to the value of right operand; if yes, the condition becomes true.(A <= B) is true.

    Logical Operators

    The following table lists all the logical operators supported by Go language. Assume variable A holds 1 and variable B holds 0, then −

    Show Examples

    OperatorDescriptionExample
    &&Called Logical AND operator. If both the operands are non-zero, then condition becomes true.(A && B) is false.
    ||Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true.(A || B) is true.
    !Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.!(A && B) is true.

    The following table shows all the logical operators supported by Go language. Assume variable A holds true and variable B holds false, then −

    OperatorDescriptionExample
    &&Called Logical AND operator. If both the operands are false, then the condition becomes false.(A && B) is false.
    ||Called Logical OR Operator. If any of the two operands is true, then the condition becomes true.(A || B) is true.
    !Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make it false.!(A && B) is true.

    Bitwise Operators

    Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows −

    pqp & qp | qp ^ q
    00000
    01011
    11110
    10011

    Assume A = 60; and B = 13. In binary format, they will be as follows −

    A = 0011 1100

    B = 0000 1101

    —————–

    A&B = 0000 1100

    A|B = 0011 1101

    A^B = 0011 0001

    ~A  = 1100 0011

    The Bitwise operators supported by C language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −

    Show Examples

    OperatorDescriptionExample
    &Binary AND Operator copies a bit to the result if it exists in both operands.(A & B) will give 12, which is 0000 1100
    |Binary OR Operator copies a bit if it exists in either operand.(A | B) will give 61, which is 0011 1101
    ^Binary XOR Operator copies the bit if it is set in one operand but not both.(A ^ B) will give 49, which is 0011 0001
    <<Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.A << 2 will give 240 which is 1111 0000
    >>Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.A >> 2 will give 15 which is 0000 1111

    Assignment Operators

    The following table lists all the assignment operators supported by Go language −

    Show Examples

    OperatorDescriptionExample
    =Simple assignment operator, Assigns values from right side operands to left side operandC = A + B will assign value of A + B into C
    +=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operandC += A is equivalent to C = C + A
    -=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operandC -= A is equivalent to C = C – A
    *=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operandC *= A is equivalent to C = C * A
    /=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operandC /= A is equivalent to C = C / A
    %=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operandC %= A is equivalent to C = C % A
    <<=Left shift AND assignment operatorC <<= 2 is same as C = C << 2
    >>=Right shift AND assignment operatorC >>= 2 is same as C = C >> 2
    &=Bitwise AND assignment operatorC &= 2 is same as C = C & 2
    ^=bitwise exclusive OR and assignment operatorC ^= 2 is same as C = C ^ 2
    |=bitwise inclusive OR and assignment operatorC |= 2 is same as C = C | 2

    Miscellaneous Operators

    There are a few other important operators supported by Go Language including sizeof and ?:.

    Show Examples

    OperatorDescriptionExample
    &Returns the address of a variable.&a; provides actual address of the variable.
    *Pointer to a variable.*a; provides pointer to a variable.

    Operators Precedence in Go

    Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator.

    For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

    Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

    Show Examples

    CategoryOperatorAssociativity
    Postfix() [] -> . ++ – –Left to right
    Unary+ – ! ~ ++ – – (type)* & sizeofRight to left
    Multiplicative* / %Left to right
    Additive+ –Left to right
    Shift<< >>Left to right
    Relational< <= > >=Left to right
    Equality== !=Left to right
    Bitwise AND&Left to right
    Bitwise XOR^Left to right
    Bitwise OR|Left to right
    Logical AND&&Left to right
    Logical OR||Left to right
    Assignment= += -= *= /= %=>>= <<= &= ^= |=Right to left
    Comma,Left to right