Go - Keywords



Go is a popular programming language that has gained significant popularity in recent years. One of the reasons for its popularity is the simplicity and readability of its syntax, which is aided by the use of keywords. Keywords in Go are reserved words that have specific meanings and cannot be used for any other purpose. In this article, we'll explore some of the most important keywords in Go and what they are used for.

Go has a total of 25 keywords, each with its own unique purpose. Here are some of the most commonly used keywords in Go

1. break

The break statement is used to exit a loop or switch statement.

Syntax

Following is the syntax for a break statement as follows −

break;

Example

In this example, we iterates through a list of numbers and display each one until it finds the target number '3'. When the target number is found, it prints and exits the loop using the break statement and indicates that the loop has ended.

package main
import (
    "fmt"
)
func main() {
   n := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
   t := 3
   for _, num := range n {
      if num == t {
         fmt.Printf("Found the target number: %d\n", num)
         break
      }
      fmt.Printf("Current number: %d\n", num)
   }
   fmt.Println("Loop ended.")
}

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

Current number: 1
Current number: 2
Found the target number: 3
Loop ended.

2. case

The case statement is used in a switch statement to specify a possible match for the input value.

Syntax

Following is the syntax for a case statement as follows −

switch case {
case value1:
case value2:
default:
}

Example

In this example, we use a switch statement with case keywords to display the day of the week based on the value of dayOfWeek. If the value matches a case (e.g: 4), it prints the corresponding day (Thursday); otherwise, it defaults to "Invalid day of the week."

package main
import (
   "fmt"
)
func main() {
   dayOfWeek := 4
   
   switch dayOfWeek {
   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 day of the week")
   }
}

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

Thursday

3. chan (channel)

The chan keyword is used to create a channel for communication between goroutines.

Syntax

Following is the syntax for a chan (channel) as follows −

ch := make(chan DataType)

Example

The program demonstrates the use of a channel to communicate between two goroutines. A message is sent from a goroutine to the main goroutine through the channel after a 2-second delay, the main goroutine receives and prints the message.

package main
import (
   "fmt"
   "time"
)
func main() {
   messages := make(chan string)
   go func() {
      time.Sleep(2 * time.Second)
      messages <- "Hello from goroutine!"
   }()
   msg := <-messages
   fmt.Println(msg)
}

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

Hello from goroutine!

4. const (constant value)

The const keyword is used to define a constant value that cannot be changed.

Syntax

Following is the syntax for a const value as follows −

const constantName = value

Example

In this example, we define a constant 'pi' and uses it to calculate the area of a circle with a given radius.then it prints the area of the circle based on the calculated value.

package main
import (
   "fmt"
)
const pi = 3.14159
func main() {
   radius := 5.0
   area := pi * radius * radius
   fmt.Printf("The area of a circle with radius %.2f is %.2f\n", radius, area)
}

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

The area of a circle with radius 5.00 is 78.54

5. continue

The continue statement is used to skip the current iteration of a loop and move to the next iteration.

Syntax

Following is the syntax for a continue statement as follows −

for condition {
    if someCondition {
        continue
    }
}

Example

The program uses a 'for' loop to iterate the numbers from 1 to 10 and prints only the odd numbers because the 'continue' keyword is used to skip the even numbers and move to the next iteration of the loop.

package main
import (
   "fmt"
)
func main() {
   for i := 1; i <= 10; i++ {
      if i%2 == 0 {
         continue // Skip even numbers
      }
      fmt.Println(i)
   }
}

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

1
3
5
7
9

6. defer

The defer keyword is used to schedule a function call to be executed after the current function returns.

Syntax

Following is the syntax for a defer statement as follows −

defer functionName(arguments)

Example

package main
import "fmt"
func main() {
   fmt.Println("Start")
   defer fmt.Println("Deferred message")
   fmt.Println("End")
}

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

Start
End
Deferred message

7. else

The else condition is used to specify an alternative block of code to execute if the if condition is false.

Syntax

Following is the syntax for a else condition as follows −

if condition {
} else {
}

Example

In this example, we check if the variable 'num' is greater than 0. If it is, it prints "The number is positive." If it is not, the 'else' block executes and prints "The number is non-positive".

package main
import "fmt"
func main() {
   num := -4
   if num > 0 {
      fmt.Println("The number is positive")
   } else {
      fmt.Println("The number is non-positive")
   }
}

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

The number is non-positive

8. fallthrough

The fallthrough is used in a switch statement to specify that control should move to the next case.

Syntax

Following is the syntax for a fallthrough case as follows −

switch expression {
case condition1:
   fallthrough
case condition2:
default:
}

Example

In this example, we check the value of the variable day and prints "Today is Wednesday" when the day is "Wednesday." Due to the fallthrough keyword, it proceeds to execute the next case, printing "Today is Thursday."

package main
import "fmt"
func main() {
   day := "Wednesday"
   switch day {
   case "Monday":
      fmt.Println("Today is Monday")
   case "Tuesday":
      fmt.Println("Today is Tuesday")
   case "Wednesday":
      fmt.Println("Today is Wednesday")
      fallthrough
   case "Thursday":
      fmt.Println("Today is Thursday")
   default:
      fmt.Println("It's some other day")
   }
}

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

Today is Wednesday
Today is Thursday

9. for

The for loop is used to create a loop that repeats a block of code a specified number of times.

Syntax

Following is the syntax for a for loop as follows −

for initialization; condition; update {

}

Example

In this example, we use a for loop to iterate from 0 to 4. For each iteration, it prints the current value of i to the console.

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

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

0
1
2
3
4

10. func (function)

The func keyword is used to define a function that can be called from other parts of the program.

Syntax

Following is the syntax for a fuction as follows −

func functionName(parameters) returnType {

}

Example

In this example, we define a function as "func add" that takes two integers, adds them. The main function calls add with the arguments 3 and 4 that stores the result in sum and display the output as 7.

package main
import "fmt"
func add(a int, b int) int {
   return a + b
}
func main() {
   sum := add(3, 4)
   fmt.Println(sum)
}

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

7

11. go (goroutine)

The go keyword is used to start a new goroutine.

Syntax

Following is the syntax for a go(goroutine) as follows −

go functionName(parameters)

Example

In this example, we start a new goroutine using the go keyword to call the sayHello function. Then the main function pauses for one second to ensure the goroutine has enough time to complete before the program exits.

package main
import (
   "fmt"
   "time"
)
func sayHello() {
   fmt.Println("Hello, world!")
}
func main() {
   go sayHello()
   time.Sleep(time.Second)
}

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

Hello, world!

12. goto

The goto keyword is used to jump to a specific label within the current function.

Syntax

Following is the syntax for a goto as follows −

goto label
label:

Example

In this example, we print "Revathi" to the console, then uses the goto statement to skip the next print statement. then it jumps to the label Skip and prints "Indumathi."

package main
import "fmt"
func main() {
   fmt.Println("Revathi")
   goto Skip
   fmt.Println("This will be skipped")
Skip:
   fmt.Println("Indumathi")
}

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

Revathi
Indumathi

13. if

The if condition is used to execute a block of code only if a certain condition is true.

Syntax

Following is the syntax for a if condition as follows −

if condition {
   true
} else {
   false
}

Example

In this example, we checks if the variable 'num' is divisible by 2 using the if condition. If it is, it prints "The number is even." Otherwise, it prints "The number is odd."

package main
import "fmt"
func main() {
   num := 8
   if num%2 == 0 {
      fmt.Println("The number is even")
   } else {
      fmt.Println("The number is odd")
   }
}

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

The number is even

14. import

The import keyword is used to import a package into the program.

Syntax

Following is the syntax for a import as follows −

import "packageName"

Example

This program imports the 'fmt' and 'math' packages. It uses the 'math.Sqrt' function to calculate the square root of 16 and prints the result, which is 4.

package main
import (
   "fmt"
   "math"
)
func main() {
   fmt.Println(math.Sqrt(16))
}

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

4

15. interface

The interface is used to define a set of methods that a type must implement.

Syntax

Following is the syntax for a Interface as follows −

type InterfaceName interface {
    methodName() returnType
}

Example

In this example, we define an Animal interface with a Speak method. A Dog struct implements this method returning "Woof". The 'main' function creates a 'Dog' instance as an 'Animal' type and prints "Woof."

package main
import "fmt"
type Animal interface {
   Speak() string
}
type Dog struct{}
func (d Dog) Speak() string {
   return "Woof"
}
func main() {
   var animal Animal = Dog{}
   fmt.Println(animal.Speak())
}

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

Woof

16. map

A map keyword is used to define a collection of key-value pairs.

Syntax

Following is the syntax for a map as follows −

var mapName map[keyType]valueType

Example

In this program, we initializes a map called 'capitals' that stores country names as keys and their capital cities as values.Then it prints the capital of France, which is "Paris".

package main
import "fmt"
func main() {
   capitals := map[string]string{
      "France": "Paris",
      "Italy":  "Rome",
   }
   fmt.Println(capitals["France"])
}

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

Paris

17. package

The package keyword is used to define a package that contains one or more Go source files.

Syntax

Following is the syntax for a package as follows −

package packageName

Example

In this example, we import the 'fmt' package and uses the 'fmt.Println' function to print the message "Hello, world!".

package main
import "fmt"
func main() {
    fmt.Println("Hello, world!")
}

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

Hello, world!

18. range

The range keyword is used to iterate over an array, slice, string, map, or channel.

Syntax

Following is the syntax for a range as follows −

for index, value := range collection {

}

Example

In this example, we initialize a slice of integers called 'nums' with the values 2, 4, and 6. Then it uses a 'for' loop with the 'range' keyword to iterate over the slice and prints each index and its corresponding value.

package main
import "fmt"
func main() {
   nums := []int{2, 4, 6}
   for i, num := range nums {
      fmt.Println(i, num)
   }
}

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

0 2
1 4
2 6

19. return

The return keyword is used to exit a function and return a value to the caller.

Syntax

Following is the syntax for a return as follows −

return value

Example

In this example, we define a function 'add' that takes two integers and returns their sum. The main function calls 'add' with the values 3 and 4 and assigns the result to 'sum' which is 7.

package main
import "fmt"
func add(a int, b int) int {
   return a + b
}
func main() {
   sum := add(3, 4)
   fmt.Println(sum)
}

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

7

20. select

The select keyword is used to wait for a value to be sent to one of several channels.

Syntax

Following is the syntax for a select as follows −

select {
case <-channel1:
case <-channel2:
default:
}

Example

In this program, we create two channels and two goroutines, each sending a message to their respective channels after a delay. The 'select' statement waits for a message from either channel and prints the first message it receives.

package main
import (
   "fmt"
   "time"
)
func main() {
   ch1 := make(chan string)
   ch2 := make(chan string)
   go func() {
      time.Sleep(2 * time.Second)
      ch1 <- "Channel 1"
   }()
   go func() {
      time.Sleep(1 * time.Second)
      ch2 <- "Channel 2"
   }()
   select {
   case msg1 := <-ch1:
      fmt.Println(msg1)
   case msg2 := <-ch2:
      fmt.Println(msg2)
   }
}

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

Channel 2

21. struct

The struct keyword is used to define a collection of fields that represent a complex data type.

Syntax

Following is the syntax for a struct as follows −

type StructName struct {
    field1 type1
    field2 type2
}

Example

In this example, we define a 'Person' struct with 'Name' and 'Age' fields. Then it creates an instance of 'Person' with the name "Revathi", age 24 and display it to the console.

package main
import "fmt"
type Person struct {
   Name string
   Age  int
}
func main() {
   p := Person{Name: "Revathi", Age: 24}
   fmt.Println(p.Name, p.Age)
}

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

Revathi 24

22. switch

The switch keyword is used to execute a block of code based on the value of an expression.

Syntax

Following is the syntax for a switch as follows −

switch expression {
case condition1:
case condition2:
default:
}

Example

In this program, we uses a switch statement to evaluate the value of the variable day and print the corresponding message. Since day is set to "Wednesday," it executes the default case and prints "It's neither Monday nor Tuesday."

package main
import "fmt"
func main() {
   day := "Tuesday"
   switch day {
   case "Monday":
      fmt.Println("Today is Monday")
   case "Tuesday":
      fmt.Println("Today is Tuesday")
   default:
      fmt.Println("It's neither Monday nor Tuesday")
   }
}

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

Today is Tuesday

23. type

The type keyword is used to define a new data type.

Syntax

Following is the syntax for a type as follows −

type TypeName type

Example

In this program, we define a new type Age as an integer. then we declare a variable age of type Age with the value 25 and prints this value to the console.

package main
import "fmt"
type Age int
func main() {
   var age Age = 24
   fmt.Println(age)
}

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

24

24. var (variable)

The var keyword is used to declare a variable.

Syntax

Following is the syntax for a var as follows −

var variableName type = value

Example

In this program, we declare a string variable 'name' with the value "Tapas" and uses the 'fmt.Println' function to print the value of name.

package main
import "fmt"
func main() {
   var name string = "Tapas"
   fmt.Println(name)
}

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

Tapas

25. default

The default keyword is used to run the program when no cases match in a switch statement.

Syntax

Following is the syntax for a default as follows −

switch expression {
case condition1:
case condition2:
default:
}

Example

This program uses a 'switch' statement to evaluate the value of the variable day. Since day is set to "Sunday", it executes the 'default' case and prints that "It's not Monday or Tuesday".

package main
import "fmt"
func main() {
   day := "Sunday"
   switch day {
   case "Monday":
      fmt.Println("Today is Monday")
   case "Tuesday":
      fmt.Println("Today is Tuesday")
   default:
      fmt.Println("It's not Monday or Tuesday")
   }
}

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

It's not Monday or Tuesday

We have explored some of the most important keywords in Go and what they are used for. By understanding the purpose of these keywords, you'll be able to write more effective and efficient Go code. Whether you're a beginner or an experienced developer, mastering Go keywords is an important step towards becoming a proficient Go programmer.

Advertisements