Go Language Fundamentals
Data Types
Go offers various built-in data types to represent different kinds of data. Some commonly used data types include:
- Integer Types:
int
: Represents a signed integer of varying size depending on the architecture. https://golang.org/ref/spec#Numeric_typesuint
: Represents an unsigned integer of varying size depending on the architecture. https://golang.org/ref/spec#Numeric_typesint8
,int16
,int32
,int64
: Represent signed integers of specific sizes. https://golang.org/ref/spec#Numeric_typesuint8
,uint16
,uint32
,uint64
: Represent unsigned integers of specific sizes. https://golang.org/ref/spec#Numeric_types
- Floating-Point Types:
float32
: Represents single-precision floating-point numbers. https://golang.org/ref/spec#Numeric_typesfloat64
: Represents double-precision floating-point numbers. https://golang.org/ref/spec#Numeric_types
- Boolean Type:
bool
: Represents a truth value, eithertrue
orfalse
. https://golang.org/ref/spec#Boolean_types
- String Type:
string
: Represents a sequence of characters. https://golang.org/ref/spec#String_types
Example:
package main
import "fmt"
func main() {
var age int = 25
var isStudent bool = true
var name string = "John Doe"
fmt.Println("Age:", age)
fmt.Println("Is Student:", isStudent)
fmt.Println("Name:", name)
}
Variables
Variables in Go store data values. They are declared using the var
keyword followed by the variable name and data type. Optionally, an initial value can be assigned during declaration.
Example:
package main
import "fmt"
func main() {
var age int = 25
var isStudent bool
var name string = "John Doe"
fmt.Println("Age:", age)
fmt.Println("Is Student:", isStudent)
fmt.Println("Name:", name)
}
Constants
Constants in Go represent fixed values that cannot be changed during program execution. They are declared using the const
keyword.
Example:
package main
import "fmt"
func main() {
const PI = 3.14159
fmt.Println("PI:", PI)
}
Operators
Go provides various operators for performing operations on data. Common operators include:
- Arithmetic Operators:
+
,-
,*
,/
,%
- Comparison Operators:
==
,!=
,>
,<
,>=
,<=
- Logical Operators:
&&
,||
,!
- Assignment Operators:
=
,+=
,-=
,*=
,/=
,%=
,&=
,|=
,^=
,<<=
,>>=
- Bitwise Operators:
&
,|
,^
,~
,<<
,>>
Example:
package main
import "fmt"
func main() {
var num1 int = 10
var num2 int = 5
sum := num1 + num2
difference := num1 - num2
product := num1 * num2
quotient := num1 / num2
remainder := num1 % num2
fmt.Println("Sum:", sum)
fmt.Println("Difference:", difference)
fmt.Println("Product:", product)
fmt.Println("Quotient:", quotient)
fmt.Println("Remainder:", remainder)
}
Control Flow
Go uses control flow statements to dictate the execution order of code. Common control flow statements include:
- if/else Statement: Executes code blocks based on a condition. https://golang.org/ref/spec#If_statements
- switch Statement: Evaluates an expression and executes the code block associated with the matching case. https://golang.org/ref/spec#Switch_statements
- for Loop: Iterates over a sequence of values. https://golang.org/ref/spec#For_statements
- break Statement: Exits the current loop. https://golang.org/ref/spec#Break_statements
- continue Statement: Skips the current iteration of the loop. https://golang.org/ref/spec#Continue_statements
Example:
package main
import "fmt"
func main() {
for i := 0; i < 5; i++ {
fmt.Println("Iteration:", i)
}
age := 25
if age >= 18 {
fmt.Println("You are an adult.")
} else {
fmt.Println("You are a minor.")
}
day := "Monday"
switch day {
case "Monday":
fmt.Println("It's the start of the week.")
case "Friday":
fmt.Println("It's the end of the week.")
default:
fmt.Println("It's another day.")
}
}
Functions
Functions in Go are reusable blocks of code that perform specific tasks. They are defined using the func
keyword followed by the function name, parameters, and return type.
Example:
package main
import "fmt"
func add(num1 int, num2 int) int {
return num1 + num2
}
func main() {
result := add(10, 5)
fmt.Println("Sum:", result)
}
Arrays and Slices
Arrays in Go are fixed-size collections of elements of the same data type. Slices are dynamic arrays that provide more flexibility. https://golang.org/doc/effective_go.html#slices
Example:
package main
import "fmt"
func main() {
var numbers [5]int = [5]int{1, 2, 3, 4, 5}
fmt.Println("Array:", numbers)
fruits := []string{"Apple", "Banana", "Orange"}
fmt.Println("Slice:", fruits)
// Appending to a slice
fruits = append(fruits, "Mango")
fmt.Println("Slice after appending:", fruits)
}
Maps
Maps in Go are key-value pairs. They provide a way to store and retrieve data using keys. https://golang.org/doc/effective_go.html#maps
Example:
package main
import "fmt"
func main() {
studentGrades := map[string]int{"John": 85, "Jane": 90, "Peter": 75}
fmt.Println("John's Grade:", studentGrades["John"])
// Adding a new entry
studentGrades["Mary"] = 80
fmt.Println("Updated Grades:", studentGrades)
}
Pointers
Pointers in Go store memory addresses of variables. They allow for direct access to data stored in memory. https://golang.org/doc/effective_go.html#pointers
Example:
package main
import "fmt"
func main() {
var num1 int = 10
var ptr *int = &num1
fmt.Println("Value of num1:", num1)
fmt.Println("Address of num1:", ptr)
fmt.Println("Value pointed by ptr:", *ptr)
// Modifying the value through the pointer
*ptr = 20
fmt.Println("Modified value of num1:", num1)
}
Structs
Structs in Go are user-defined data types that group together related data fields. https://golang.org/doc/effective_go.html#structs
Example:
package main
import "fmt"
type Person struct {
Name string
Age int
City string
}
func main() {
person := Person{"John Doe", 25, "New York"}
fmt.Println("Person:", person)
}
Interfaces
Interfaces in Go define a set of methods that a type must implement. They enable polymorphism and loose coupling. https://golang.org/doc/effective_go.html#interfaces
Example:
package main
import "fmt"
type Animal interface {
Speak() string
}
type Dog struct {
}
func (d Dog) Speak() string {
return "Woof!"
}
type Cat struct {
}
func (c Cat) Speak() string {
return "Meow!"
}
func main() {
var animal Animal
animal = Dog{}
fmt.Println(animal.Speak())
animal = Cat{}
fmt.Println(animal.Speak())
}
Error Handling
Go utilizes the concept of “errors” for handling exceptional situations. https://golang.org/doc/effective_go.html#errors
Example:
package main
import "fmt"
func divide(num1 int, num2 int) (int, error) {
if num2 == 0 {
return 0, fmt.Errorf("Cannot divide by zero.")
}
return num1 / num2, nil
}
func main() {
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
}