Keywords in Go


December 30, 2021, Learn eTutorial
2518

In a programming language, a keyword is a predefined word that has some special meaning. Keywords are already reserved by the programming language to perform some predefined actions. The keywords are also called reserved words or reserved names. These words are not allowed to be used as an identifier, otherwise, a compile-time error will occur which will interrupt the program execution.
There are 25 keywords in the Go programming language. They are as follows:

GO : Tokens

These keywords can be divided into four groups based on their usage:

Declaration Composite Control Flow Function Modifier

const

chan

break

defer

var

interface

case

go

func

map

continue

 

type

struct

default

 

import

 

else

 

package

 

fallthrough

 

 

 

for

 

 

 

goto

 

 

 

if

 

 

 

range

 

 

 

return

 

 

 

select

 

 

 

switch

 

Let’s learn each one of them…

    Declaration keywords

Declaration keywords are used to declare the various elements of the Go programming language.

  • const

    In the Go programming language, the "const" keyword is used for the declaration of a constant value. Once a value is declared as a constant value, then it is not possible to change or re-assign a new value to it.

    
    const CONST_NAME type = value
    
    
    
    const C
    

    Example program to print values of constant variables:

    
    
    package main
    import ("fmt")
    
    func main() {
      const A int= 1
      const B = 2
    
      fmt.Println(A)
      fmt.Println(B)
    }
    
    

    Output:

    
    1
    2
    
  • var

    In the Go programming language, the "var" keyword is used for the declaration of a variable. Variables are used to store the values in the computer memory locations.

    Syntax

    
    var variable_name type = value
    
    
    
    variable_name := value
    
    

    Example program to print values of variables:

    
    package main
    import ("fmt")
    
    func main() {
      var variable_1 string = "Hello" 
      var variable_2 = "World" 
      a := 5 
    
      fmt.Println(variable_1)
      fmt.Println(variable_2)
      fmt.Println(a)
    }
    
    

    Output:

    
    Hello
    World
    5
    
  • func

    In the Go programming language, the "func" keyword is used to create (or declare) a function. In a program, a function is a block of codes to perform some specific tasks. The code inside of a function is only executed when the function is invoked.

    Syntax

    
    func FunctionName() {
     //codes of statements of the function
    }
    
    

    Example program to print a message using a function:

    
    package main
    import ("fmt")
    
    func Fun_Msg() {
      fmt.Println(" This is a message from the function ! ")
    }
    
    func main() {
      Fun_Msg() 
    }
    
    

    Output:

    
    This is a message from the function !
    
  • type

    In the Go programming language, the "type" keyword is used to create a new type such as struct(structure), interface, pointer, etc.

    Syntax

    
    type type_name existing_type or type_definition
    
    

    Example program to print details of a person using struct:

    
    package main
    import ("fmt")
    
    type Person struct {
      name string
      age int
    }
    
    func main() {
      var p1 Person
      
      p1.name = "Mary"
      p1.age = 30
    
      fmt.Println("Name: ", p1.name)
      fmt.Println("Age: ", p1.age)
    
    }
    
    

    Output:

    
    Name: Mary
    Age: 30
    

    Note: In the Go programming language, a struct or structure is used to combine items/values of different types into a single type.

  • package

    In the Go programming language, the keyword "package" is used to declare a package. A package is used to combine related features of large numbers of programs into single units. It will be easier to maintain and understand the programs by using the packages A Go program must have the "main" package, otherwise, it will not be compiled.
    Syntax

    
    package package_name
    
    
     package main
    
    
  • import

    In the Go programming language, the keyword "import" is used to link various packages into the program.
    Syntax

    
    Import “package_name”
    
    

    Example

    
     import “fmt”
     import “ost”
    
    

Composite keywords

Composite type keywords are used to represent composite types.

  • chan

    In the Go programming language, the keyword "chan" is used to define a channel. A channel is a medium used to communicate between the goroutines.
    Syntax

        
    var channel_name chan type
    
       

    Example

        
    package main
    import "fmt"
    func main() {
      
        var my_channel chan int
        fmt.Println("Value of channel: ", my_channel)
        fmt.Printf("Type of channel: %T ", my_channel)
    }  
    
       

    Output:

        
    Value of channel: 
    Type of channel: chan int
    
       
  • interface

    In the Go programming language, the keyword "interface" is used to represent a set of method signatures.
    Syntax

        
    type name_of_interface interface{
    //methods
    }
    
       

    Example

        
    package main
    import "fmt"
    type square interface {
        sarea() float64
        sperimeter() float64
    }
    type myvalue struct {
        side float64
    }
    func (m myvalue) sarea() float64 {
        return m.side*m.side
    }
    func (m myvalue) sperimeter() float64 {
        return 4*m.side
    }
    func main() { 
        var s square
        s = myvalue{2}
        fmt.Println("Area of square :", s.sarea())
        fmt.Println("Perimeter of square:", s.sperimeter())
    }
    
       

    Output:

        
    Area of square :4
    Perimeter of square:8
    
       
  • map

    In the Go programming language, the keyword "map" is used to define a map type. A map is a collection of unordered key-value pairs. Maps are used to perform lookups, update, delete, and retrieve values.

        
    var map_variable = map[key_type]value_type{key1:value1, key2:value2,……..}
       

    Example

        
    package main
    import ("fmt")
    
    func main() {
      var m = map[string]string{"Name": "Joy", "breed": "Siberian Husky", "age": "2021"}
      fmt.Printf("m\t%v\n", m)
    }  

    Output:

    m map[{Name: Joy age: 2021 breed: Siberian Husky]
       
  • struct

    In the Go programming language, the keyword "struct" is used to declare a structure. A structure is used to store a collection of values/members of different data types into a single variable.
    Syntax

        
    type struct_name struct {
      member1 datatype;
      member2 datatype;
      member3 datatype;
      member4 datatype;
     ..........
    }
    
       

    Example

        
    package main
    import ("fmt")
    
    type Employee struct {
      name string
      age int
      salary int
    }
    
    func main() {
      var emp1 Employee
      var emp2 Employee
    
      emp1.name = "Alex"
      emp1.age = 30
      emp1.salary = 10000
    
      emp2.name = "Mary"
      emp2.age = 50
      emp2.salary = 12000
    
      fmt.Println("Name: ", emp1.name)
      fmt.Println("Age: ", emp1.age)
      fmt.Println("Salary: ", emp1.salary)
      
      fmt.Println("Name: ", emp2.name)
      fmt.Println("Age: ", emp2.age)
      fmt.Println("Salary: ", emp2.salary)
    }
    
       

    Output:

        
    Name: Alex
    Age:30
    Salary:10000
    Name: Mary
    Age:50
    Salary:12000
    
       

Control Flow

These keywords are used to control the flow of the code. It is also referred to as decision making, and it means that a block of codes is executed based on the given conditions.

  • if

    The "if" keyword is used to execute a block of code(s) when the given condition is true, and if the given condition is false then the block of code will not be executed.
    Syntax

    
    if condition {
     //codes to be executed if the condition is true
    }
    
    

    Example program to print the largest number of two numbers:

    
    package main
    import ("fmt")
    
    func main() {
      a := 10
      b := 2
      if a>b {
        fmt.Println(" The largest number is", a)
      }
    }
    
    

    Output:

    
    The largest number is 10
    
  • else

    The "else" keyword is used with the "if" keyword to execute another block of code(s) when the given condition is false.

    Syntax

    
    if condition {
     //codes to be executed if the condition is true
    } else {
    // codes to be executed if the condition is false
    }
    
    

    Example program to print the largest number of two numbers:

    
    package main
    import ("fmt")
    
    func main() {
      a := 3
      b := 6
      if a>b {
        fmt.Println(" The largest number is", a)
      } else {
       fmt.Println(" The largest number is", b)
      }
    }
    
    

    Output:

    
    The largest number is 6
    
  • for

    The "for" keyword is used to execute a block of code(s) repeatedly with a different value each time.
    Syntax

    
    for initialization; condition; increment/decrement {
     // codes to be executed
    }
    
    

    Example program to print numbers up to 10:

    
    package main
    import ("fmt")
    
    func main() {
      for i:=1; i <= 10; i++ {
        fmt.Println(i)
      }
    }
    
    

    Output:

    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
  • continue

    The "continue" keyord is used with the "for" keyword to skip iterations(s) and then continues with the next iteration in the loop

    Example program to print numbers up to 5 and skip one number:

    
    package main
    import ("fmt")
    
    func main() {
      for i:=1; i <= 5; i++ {
        if i == 2 {
          continue
        }
        fmt.Println(i)
      }
    }
    
    

    Output:

    
    1
    3
    4
    5
    
  • break

    The "break" keyword is used to terminate a loop. After the termination of the loop, the rest of the code will be executed.

    Example program to print numbers up to 10 and terminate the loop after 5:

    
    package main
    import ("fmt")
    
    func main() {
    
      for i:=1; i <= 10; i++ {
        if i == 6 {
          break
        }
        fmt.Println(i)
      }
    }
    
    

    Output:

    
    1
    2
    3
    4
    5
    
  • goto

    The "goto" keyword is used in a function to jump to a labeled statement without any conditions.
    Syntax

    
    label: statements
    …..
    ….
    goto label
    
    

    Example

    
    package main
    import "fmt"
    func main() { 
       a := 1
       LABEL: for a <= 5 {
          if a == 2 {
             a = a + 1
             goto LABEL
          }
          fmt.Printf("value of a = %d\n", a)
          a++     
       }  
    }
    
    

    Output:

    
    Output:
    value of a = 1
    value of a = 3
    value of a = 4
    value of a = 5
    
  • switch

    The "switch" keyword is used to execute a block of codes from many blocks of codes.

  • case

    The "case" keyword is used with the "switch" statement. In the switch statement, the expression is compared with multiple case values. If this expression matches with a case value, then the codes associated with the case will be executed.
    Syntax

    
    switch expression {
     case a:
      // code of block
     case b:
      // code of block
     case c:
      // code of block
     ……………
    }
    
    

    Example program to print the name of the month:

    
    package main
    import ("fmt")
    
    func main() {
      
      month := 2
    
      switch month {
      case 1:
        fmt.Println("January")
      case 2:
        fmt.Println("February")
      case 3:
        fmt.Println("March")
      case 4:
        fmt.Println("April")
      case 5:
        fmt.Println("May")
      case 6:
        fmt.Println("June")
      case 7:
        fmt.Println("July")
      case 8:
        fmt.Println("August")
      case 9:
        fmt.Println("September")
      case 10:
        fmt.Println("October")
      case 11:
        fmt.Println("November")
      case 12:
        fmt.Println("December")  
      }
    }
    
    

    Output:

    
    February
    
  • default

    The "default" keyword is used with the "switch" statement to execute a block of codes when there is no case match found. This keyword is optional.
    Syntax

    
    switch expression {
     case a:
      // code of block
     case b:
      // code of block
     case c:
      // code of block
     ……………
    default:
     // code of block
    }
    
    

    Example program

    
    package main
    import ("fmt")
    
    func main() {
      var day int= 8
    
      switch day {
      case 1:
        fmt.Println("Monday")
      case 2:
        fmt.Println("Tuesday")
      case 3:
        fmt.Println("Wednesday")
      case 4:
        fmt.Println("Thursday")
      case 5:
        fmt.Println("Friday")
      case 6:
        fmt.Println("Saturday")
      case 7:
        fmt.Println("Sunday")
      default:
        fmt.Println("Invalid")
      }
    }
    
    

    Output:

    
    Invalid
    
  • fallthrough

    The "fallthrough" keyword is used inside the switch case block. It is used to transfer the program control to the next case even if the expression matches the current case.

    Example program

    
    package main
    import ("fmt")
    
    func main() {
      var day int= 5
    
      switch day {
      case 1:
        fmt.Println("Monday")
      case 2:
        fmt.Println("Tuesday")
      case 3:
        fmt.Println("Wednesday")
      case 4:
        fmt.Println("Thursday")
      case 5:
        fmt.Println("Friday")
        fallthrough
      case 6:
        fmt.Println("Saturday")
        fallthrough
      case 7:
        fmt.Println("Sunday")
      }
    }
    
    

    Output:

    
    Friday
    Saturday
    Sunday
    
  • range

    In the Go programming language, the keyword "range" is used in different types of data structures to iterate over all the elements. the range is mainly used for the loop.

    Example program

    
    package main
    import "fmt"
    func main() {
        even := [5]int{2, 4, 6, 8, 10}
        for i, item := range even {
            fmt.Printf("even[%d] = %d \n", i, item)
        }
    }
    
    

    Output:

    
    even[0] = 2 
    even[1] = 4
    even[2] = 6
    even[3] = 8
    even[4] = 10
    
  • return

    In the Go programming language, the keyword "return" is used to return values as variables.

  • select

    In the Go programming language, the keyword "select" is used for multiple channels operation. The select statement is similar to the switch statement.
    Syntax

    
    select {
        case case1:
            // case 1...
        case case2:
            // case 2...
        case case3:
            // case 3...
        case case4:
            // case 4...
        default:
                    // default case...
    }
    
    

    Example program

    
    package main
    import ("fmt")
     
    func g1(chanel chan int) {
        chanel <- 10
    }
     
    func g2(chanel chan int) {
        chanel <- 30
    }
     
    func main() {
     
        chanel1 := make(chan int)
        chanel2 := make(chan int)
     
        go g1(chanel1)
        go g1(chanel2)
     
        select {
        case v1 := <-chanel1:
            fmt.Println("Got: ", v1)
        case v2 := <-chanel2:
            fmt.Println("Got: ", v2)
        }
    }
    
    

    Output:

    
    Got: 10
    

Function modifier

The function modifier keywords are used to modify the function calls.

  • defer

    In the Go programming language, the keyword "defer" is used to delay the execution of functions or methods until the surrounding functions return.
    Syntax

    
    //function
    defer func func_name(parameter_list Type)return_type{
    // Code
    }
    
    // Method
    defer func (receiver Type) method_name(parameter_list){
    // Code
    }
    
    defer func (parameter_list)(return_type){
    // code
    }()
    
    

    Example program

    
    package main
    import "fmt"
    func mul(x, y int) int {
        r := x * y
        fmt.Println("Result: ", r)
        return 0
    }
    func show() {
        fmt.Println("Hello world")
    }
    func main() {
        mul(2, 5)
        defer mul(4, 3)
        show()
    }
    
    

    Output:

    
    Result: 10
    Hello world
    Result: 12
    
  • go

    In the Go programming language, the keyword "go" is used to create goroutines.
    Syntax

    
    func function_name(){
    // statements
    }
    go function_name()
    
    

    Example program

    
    package main
    import "fmt"
      
    func display(s string) {
        for i := 0; i < 5; i++ {
            fmt.Println(s)
        }
    }
    func main() {
        go display("Welcome")
        display("hello")
    }
    
    

    Output:

    
    hello
    hello
    hello
    hello
    hello