Table of Contents
- Getting Started
- Basic Syntax
- Data Types
- Control Structures
- Functions
- Structs and Interfaces
- Concurrency
1. Installation
To install Go, download it from the official website and follow the installation instructions for your operating system.
Create a new Go file with the .go
extension, for example, main.go
.
2. Basic Syntax
Hello, World!
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Start
- The
main
package is required for executable commands. - The
main
function is the entry point of a Go program. -
fmt
is a standard library package for formatted I/O.
3. Data Types
Variable Declaration
var name string = "Go"
var age int = 10
Short Variable Declaration
name := "Go"
age := 10
Constants
const Pi = 3.14
Basic Types
-
Integers:
int
,int8
,int16
,int32
,int64
-
Unsigned Integers:
uint
,uint8
,uint16
,uint32
,uint64
-
Floats:
float32
,float64
-
Complex:
complex64
,complex128
-
Others:
byte
(alias foruint8
),rune
(alias forint32
),bool
,string
4. Control Structures
If-Else
if age > 18 {
fmt.Println("Adult")
} else {
fmt.Println("Minor")
}
For Loop
for i := 0; i < 5; i++ {
fmt.Println(i)
}
Switch
switch day {
case "Monday":
fmt.Println("Start of the week")
case "Friday":
fmt.Println("End of the week")
default:
fmt.Println("Midweek")
}
5. Functions
Basic Function
func add(a int, b int) int {
return a + b
}
Multiple Return Values
func swap(x, y string) (string, string) {
return y, x
}
Named Return Values
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return
}
6. Structs and Interfaces
Structs
type Person struct {
Name string
Age int
}
p := Person{Name: "Alice", Age: 30}
Methods
func (p Person) greet() string {
return "Hello, " + p.Name
}
Interfaces
type Animal interface {
Speak() string
}
type Dog struct{}
func (d Dog) Speak() string {
return "Woof"
}
7. Concurrency
Goroutines
go func() {
fmt.Println("In a goroutine")
}()
Channels
messages := make(chan string)
go func() {
messages <- "ping"
}()
msg := <-messages
fmt.Println(msg)
Select
select {
case msg1 := <-chan1:
fmt.Println("Received", msg1)
case msg2 := <-chan2:
fmt.Println("Received", msg2)
default:
fmt.Println("No message received")
}
Conclusion
This cheat sheet provides a quick overview of Go's basic syntax and features. Go's simplicity and efficiency make it an excellent choice for various applications, from web servers to distributed systems. For more detailed information, refer to the official Go documentation and Do Contact me on LinkedIn Syed Muhammad Ali Raza
Top comments (1)
Thanks for the detailed Go Lang cheatsheet! Can you explain a bit more about how channels work in concurrency?