Go Fundamentals

gophers_kisumu

Gophers Kisumu

Posted on June 17, 2024

Go Fundamentals

Basic Syntax and Structure

1. Go Program Structure

A Go program typically consists of multiple packages, and the main package serves as the entry point of the program. The basic structure of a Go program is:

package main

import "fmt"

// main function - the entry point of the program
func main() {
    fmt.Println("Hello, World!")
}
Enter fullscreen mode Exit fullscreen mode
  • Package Declaration: Every Go file begins with a package declaration. The main package is special because it defines a standalone executable program.
  • Import Statements: The import keyword is used to include other packages. For example, fmt is a package for formatted I/O operations.
  • Function Definition: Functions are defined using the func keyword. The main function is the entry point of the program.

2. Variables and Constants

Variables and constants are fundamental to any programming language, allowing the storage and manipulation of data.

  • Variables:
    • Declared using the var keyword.
    • Can be initialized when declared, or later.
  var x int
  var y int = 10
  z := 20 // shorthand for declaring and initializing a variable
Enter fullscreen mode Exit fullscreen mode
  • Constants:
    • Declared using the const keyword.
    • Cannot be changed once initialized.
  const Pi = 3.14
  const Greeting = "Hello, World!"
Enter fullscreen mode Exit fullscreen mode

3. Basic Data Types

Go has several built-in data types:

  • Strings: Represent a sequence of characters.
  var name string = "Gopher"
Enter fullscreen mode Exit fullscreen mode
  • Integers: Represent whole numbers.
  var age int = 25
Enter fullscreen mode Exit fullscreen mode
  • Floats: Represent floating-point numbers.
  var height float64 = 5.9
Enter fullscreen mode Exit fullscreen mode
  • Booleans: Represent true or false values.
  var isActive bool = true
Enter fullscreen mode Exit fullscreen mode

Control Structures

1. Conditionals

  • If Statement: Executes a block of code if a specified condition is true.
  if x > 10 {
      fmt.Println("x is greater than 10")
  }
Enter fullscreen mode Exit fullscreen mode
  • If-Else Statement: Provides an alternative block of code if the condition is false.
  if x > 10 {
      fmt.Println("x is greater than 10")
  } else {
      fmt.Println("x is 10 or less")
  }
Enter fullscreen mode Exit fullscreen mode
  • If-Else If-Else Statement: Checks multiple conditions sequentially.
  if x > 10 {
      fmt.Println("x is greater than 10")
  } else if x == 10 {
      fmt.Println("x is exactly 10")
  } else {
      fmt.Println("x is less than 10")
  }
Enter fullscreen mode Exit fullscreen mode
  • Switch Statement: An alternative to multiple if-else if statements, providing a cleaner syntax.
  switch day {
  case "Monday":
      fmt.Println("Start of the work week")
  case "Friday":
      fmt.Println("End of the work week")
  default:
      fmt.Println("It's a regular day")
  }
Enter fullscreen mode Exit fullscreen mode

2. Loops

  • For Loop: The only looping construct in Go, but it can be used in various forms.

    • Traditional For Loop:
    for i := 0; i < 10; i++ {
        fmt.Println(i)
    }
    
    • While-Like Loop:
    i := 0
    for i < 10 {
        fmt.Println(i)
        i++
    }
    
    • Infinite Loop:
    for {
        fmt.Println("Infinite loop")
    }
    

Functions

1. Defining and Calling Functions

Functions in Go are defined using the func keyword. They can have parameters and return values.

  • Basic Function:
  func greet() {
      fmt.Println("Hello, World!")
  }

  func main() {
      greet()
  }
Enter fullscreen mode Exit fullscreen mode
  • Function with Parameters:
  func add(a int, b int) int {
      return a + b
  }

  func main() {
      sum := add(5, 7)
      fmt.Println(sum)
  }
Enter fullscreen mode Exit fullscreen mode
  • Function with Multiple Return Values:
  func divide(a int, b int) (int, int) {
      quotient := a / b
      remainder := a % b
      return quotient, remainder
  }

  func main() {
      q, r := divide(10, 3)
      fmt.Println("Quotient:", q, "Remainder:", r)
  }
Enter fullscreen mode Exit fullscreen mode

2. Anonymous Functions and Closures

  • Anonymous Functions: Functions without a name, often used as literals.
  func main() {
      func() {
          fmt.Println("Anonymous function")
      }()
  }
Enter fullscreen mode Exit fullscreen mode
  • Closures: Anonymous functions that capture variables from their surrounding scope.
  func main() {
      x := 10
      increment := func() int {
          x++
          return x
      }
      fmt.Println(increment()) // Output: 11
      fmt.Println(increment()) // Output: 12
  }
Enter fullscreen mode Exit fullscreen mode

By mastering these fundamental aspects of Go, you'll be well-equipped to handle more advanced topics and build robust applications. The simplicity and clarity of Go's syntax and structures make it an excellent choice for both new and experienced developers.

đź’– đź’Ş đź™… đźš©
gophers_kisumu
Gophers Kisumu

Posted on June 17, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related