Back to: Golang
Code example that demonstrates the use of several important features of Go:
package main
import "fmt"
type Person struct {
Name string
Age int
}
func (p Person) greet() {
fmt.Printf("Hi, my name is %s and I'm %d years old\n", p.Name, p.Age)
}
func main() {
// Declare and initialize a slice of Persons
persons := []Person{
{Name: "Alice", Age: 25},
{Name: "Bob", Age: 30},
{Name: "Charlie", Age: 35},
}
// Iterate over the slice and call the greet method on each Person
for _, person := range persons {
person.greet()
}
// Declare and initialize a map of Persons
people := map[string]Person{
"Alice": {Name: "Alice", Age: 25},
"Bob": {Name: "Bob", Age: 30},
"Charlie": {Name: "Charlie", Age: 35},
}
// Iterate over the map and call the greet method on each Person
for _, person := range people {
person.greet()
}
// Declare and initialize a channel of type string
ch := make(chan string)
// Start a goroutine to send messages to the channel
go func() {
ch <- "Hello"
ch <- "World"
close(ch)
}()
// Read messages from the channel until it's closed
for message := range ch {
fmt.Println(message)
}
}
This code demonstrates the following features of Go:
- Structs and methods: the
Person
struct andgreet
method demonstrate how to define a struct and methods on it. - Slices: the
persons
slice demonstrates how to declare and initialize a slice of a custom type. - Maps: the
people
map demonstrates how to declare and initialize a map of a custom type. - Channels: the
ch
channel demonstrates how to declare and initialize a channel, and the goroutine that sends messages to it demonstrates how to start a new concurrent execution flow. - Goroutines and concurrency: the goroutine that sends messages to the channel demonstrates how to start a new concurrent execution flow, and the loop that reads messages from the channel demonstrates how to synchronize with that flow using a channel.
Follow us on social media
Follow Author