Go, also known as Golang, is a statically typed and compiled programming language developed by Google.
It's designed for simplicity, efficiency, and ease of use.
The classic "Hello, World!" program in Go is just a few lines of code. Code:
Use the 'fmt' package to print to the console.
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Go supports various data types, including integers, floats, strings, and booleans.
Declare variables using var or short declaration :=. Code:
var age int
name := "John"
Functions are defined using the func keyword.
The main function is the entry point for Go programs. Code:
func sayHello() {
fmt.Println("Hello!")
}
Go has standard control structures like if, for, and switch.
You can also use defer to schedule a function call. Code:
if x > 10 {
// do something
}
for i := 0; i < 5; i++ { // loop
}
defer cleanup()
Arrays and slices are used for collections of elements.
Maps store key-value pairs. Code:
var numbers [5]int
fruits := []string{"apple", "banana"}
studentScores := map[string]int{"Alice": 95, "Bob": 88}
Pointers hold the memory address of a variable.
Use & to get a variable's address and * to access its value. Code:
var x int
y := &x
*y = 42
Structs allow you to define custom data types with named fields.
They are often used for organizing related data. Code:
type Person struct {
Name string
Age int
}
Go organizes code into packages, which contain related functions and data.
The import statement is used to bring in packages from the standard library or third-party sources. Code:
import "fmt"
Go's built-in support for goroutines and channels simplifies concurrent programming.
Goroutines are lightweight threads, and channels enable communication between them. Code:
go doSomething()
ch := make(chan int)
Go encourages returning errors explicitly.
The error type is commonly used for this purpose.
Go uses interfaces to define sets of methods that types can implement.
This allows for polymorphism and code reusability.
The testing package is used to create unit tests for Go code.
Test functions start with "Test" and can be run using the go test command.
Documentation in Go is created using comments and the godoc tool.
Write clear, concise comments to make your code more understandable.