Author: Saim Khalid

  • 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
  • Constants

    Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.

    Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well.

    Constants are treated just like regular variables except that their values cannot be modified after their definition.

    Integer Literals

    An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.

    An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order.

    Here are some examples of integer literals −

    212         /* Legal */
    215u        /* Legal */
    0xFeeL      /* Legal */
    078         /* Illegal: 8 is not an octal digit */
    032UU       /* Illegal: cannot repeat a suffix */
    

    Following are other examples of various type of Integer literals −

    85         /* decimal */
    0213       /* octal */
    0x4b       /* hexadecimal */
    30         /* int */
    30u        /* unsigned int */
    30l        /* long */
    30ul       /* unsigned long */
    

    Floating-point Literals

    A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form.

    While representing using decimal form, you must include the decimal point, the exponent, or both and while representing using exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E.

    Here are some examples of floating-point literals −

    3.14159       /* Legal */
    314159E-5L    /* Legal */
    510E          /* Illegal: incomplete exponent */
    210f          /* Illegal: no decimal or exponent */
    .e55          /* Illegal: missing integer or fraction */
    

    Escape Sequence

    When certain characters are preceded by a backslash, they will have a special meaning in Go. These are known as Escape Sequence codes which are used to represent newline (\n), tab (\t), backspace, etc. Here, you have a list of some of such escape sequence codes −

    Escape sequenceMeaning
    \\\ character
    \’‘ character
    \”” character
    \?? character
    \aAlert or bell
    \bBackspace
    \fForm feed
    \nNewline
    \rCarriage return
    \tHorizontal tab
    \vVertical tab
    \oooOctal number of one to three digits
    \xhh . . .Hexadecimal number of one or more digits

    The following example shows how to use \t in a program −

    package main
    
    import "fmt"
    
    func main() {
       fmt.Printf("Hello\tWorld!")
    }

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

    Hello World!
    

    String Literals in Go

    String literals or constants are enclosed in double quotes “”. A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.

    You can break a long line into multiple lines using string literals and separating them using whitespaces.

    Here are some examples of string literals. All the three forms are identical strings.

    "hello, dear"
    
    "hello, \
    
    dear"
    
    "hello, " "d" "ear"
    

    The const Keyword

    You can use const prefix to declare constants with a specific type as follows −

    const variable type = value;
    

    The following example shows how to use the const keyword −

    package main
    
    import "fmt"
    
    func main() {
       const LENGTH int = 10
       const WIDTH int = 5   
       var area int
    
       area = LENGTH * WIDTH
       fmt.Printf("value of area : %d", area)   
    }

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

    value of area : 50
    
  • Ranges

    Kotlin range is defined by its two endpoint values which are both included in the range. Kotlin ranges are created with rangeTo() function, or simply using downTo or (. .) operators. The main operation on ranges is contains, which is usually used in the form of in and !in operators.

    Example

    1..10// Range of integers starting from 1 to 10
    
    a..z   // Range of characters starting from a to z
    
    A..Z   // Range of capital characters starting from A to Z

    Both the ends of the range are always included in the range which means that the 1..4 expression corresponds to the values 1,2,3 and 4.

    Creating Ranges using rangeTo()

    To create a Kotlin range we call rangeTo() function on the range start value and provide the end value as an argument.

    Example

    funmain(args: Array<String>){for( num in1.rangeTo(4)){println(num)}}

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

    1
    2
    3
    4
    

    Creating Ranges using .. Operator

    The rangeTo() is often called in its operator form ... So the above code can be re-written using .. operator as follows:

    Example

    funmain(args: Array<String>){for( num in1..4){println(num)}}

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

    1
    2
    3
    4
    

    Creating Ranges using downTo() Operator

    If we want to define a backward range we can use the downTo operator:

    Example

    funmain(args: Array<String>){for( num in4 downTo 1){println(num)}}

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

    4
    3
    2
    1
    

    Kotlin step() Function

    We can use step() function to define the distance between the values of the range. Let’s have a look at the following example:

    Example

    funmain(args: Array<String>){for( num in1..10 step 2){println(num)}}

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

    1
    3
    5
    7
    9
    

    Kotlin range of Characters

    Ranges can be created for characters like we have created them for integer values.

    Example

    funmain(args: Array<String>){for( ch in'a'..'d'){println(ch)}}

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

    a
    b
    c
    d
    

    Kotlin reversed() Function

    The function reversed() can be used to reverse the values of a range.

    Example

    funmain(args: Array<String>){for( num in(1..5).reversed()){println(num)}}

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

    5
    4
    3
    2
    1
    

    Kotlin until() Function

    The function until() can be used to create a range but it will skip the last element given.

    Example

    funmain(args: Array<String>){for( num in1 until 5){println(num)}}

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

    1
    2
    3
    4
    

    The last, first, step Elements

    We can use firstlast and step properties of a range to find the first, the last value or the step of a range.

    Example

    funmain(args: Array<String>){println((5..10).first)println((5..10 step 2).step)println((5..10).reversed().last)}

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

    5
    2
    5
    

    Filtering Ranges

    The filter() function will return a list of elements matching a given predicate:

    Example

    funmain(args: Array<String>){val a =1..10val f = a.filter{ T -> T %2==0}println(f)}

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

    [2, 4, 6, 8, 10]
    

    Distinct Values in a Range

    The distinct() function will return a list of distinct values from a range having repeated values:

    Example

    funmain(args: Array<String>){val a =listOf(1,1,2,4,4,6,10)println(a.distinct())}

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

    [1, 2, 4, 6, 10]
    

    Range Utility Functions

    There are many other useful functions we can apply to our range, like minmaxsumaveragecount:

    Example

    funmain(args: Array<String>){val a =1..10println(a.min())println(a.max())println(a.sum())println(a.average())println(a.count())}

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

    1
    10
    55
    5.5
    10
    
  • Variables

    A variable is nothing but a name given to a storage area that the programs can manipulate. Each variable in Go has a specific type, which determines the size and layout of the variable’s memory, the range of values that can be stored within that memory, and the set of operations that can be applied to the variable.

    The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Go is case-sensitive. Based on the basic types explained in the previous chapter, there will be the following basic variable types −

    Sr.NoType & Description
    1byteTypically a single octet(one byte). This is an byte type.
    2intThe most natural size of integer for the machine.
    3float32A single-precision floating point value.

    Go programming language also allows to define various other types of variables such as Enumeration, Pointer, Array, Structure, and Union, which we will discuss in subsequent chapters. In this chapter, we will focus only basic variable types.

    Variable Definition in Go

    A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows −

    var variable_list optional_data_type;
    

    Here, optional_data_type is a valid Go data type including byte, int, float32, complex64, boolean or any user-defined object, etc., and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here −

    var  i, j, k int;
    var  c, ch byte;
    var  f, salary float32;
    d =  42;
    

    The statement “var i, j, k;” declares and defines the variables i, j and k; which instructs the compiler to create variables named i, j, and k of type int.

    Variables can be initialized (assigned an initial value) in their declaration. The type of variable is automatically judged by the compiler based on the value passed to it. The initializer consists of an equal sign followed by a constant expression as follows −

    variable_name = value;
    

    For example,

    d = 3, f = 5;    // declaration of d and f. Here d and f are int 
    

    For definition without an initializer: variables with static storage duration are implicitly initialized with nil (all bytes have the value 0); the initial value of all other variables is zero value of their data type.

    Static Type Declaration in Go

    A static type variable declaration provides assurance to the compiler that there is one variable available with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail of the variable. A variable declaration has its meaning at the time of compilation only, the compiler needs the actual variable declaration at the time of linking of the program.

    Example

    Try the following example, where the variable has been declared with a type and initialized inside the main function −

    Live Demo

    package main
    
    import "fmt"
    
    func main() {
       var x float64
       x = 20.0
       fmt.Println(x)
       fmt.Printf("x is of type %T\n", x)
    }

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

    20
    x is of type float64
    

    Dynamic Type Declaration / Type Inference in Go

    A dynamic type variable declaration requires the compiler to interpret the type of the variable based on the value passed to it. The compiler does not require a variable to have type statically as a necessary requirement.

    Example

    Try the following example, where the variables have been declared without any type. Notice, in case of type inference, we initialized the variable y with := operator, whereas x is initialized using = operator.

    Live Demo

    package main
    
    import "fmt"
    
    func main() {
       var x float64 = 20.0
    
       y := 42 
       fmt.Println(x)
       fmt.Println(y)
       fmt.Printf("x is of type %T\n", x)
       fmt.Printf("y is of type %T\n", y)	
    }

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

    20
    42
    x is of type float64
    y is of type int
    

    Mixed Variable Declaration in Go

    Variables of different types can be declared in one go using type inference.

    Example

    Live Demo

    package main
    
    import "fmt"
    
    func main() {
       var a, b, c = 3, 4, "foo"  
    	
       fmt.Println(a)
       fmt.Println(b)
       fmt.Println(c)
       fmt.Printf("a is of type %T\n", a)
       fmt.Printf("b is of type %T\n", b)
       fmt.Printf("c is of type %T\n", c)
    }

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

    3
    4
    foo
    a is of type int
    b is of type int
    c is of type string
    

    The lvalues and the rvalues in Go

    There are two kinds of expressions in Go −

    • lvalue − Expressions that refer to a memory location is called “lvalue” expression. An lvalue may appear as either the left-hand or right-hand side of an assignment.
    • rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment.

    Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side.

    The following statement is valid −

    x = 20.0
    

    The following statement is not valid. It would generate compile-time error −

    10 = 20