Here are some advanced Go code examples for beginners:
Example 1: Using a Map to Count the Frequency of Words in a Text File
go
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
m := make(map[string]int)
file, err := os.Open("example.txt")
if err != nil {
fmt.Println("Error:", err)
return
}
defer file.Close()
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
word := strings.ToLower(scanner.Text())
m[word]++
}
fmt.Println(m)
}
Example 2: Using a Struct to Represent a Rectangle and a Method to Calculate Its Area
go
package main
import "fmt"
type Rectangle struct {
Width float64
Height float64
}
func (r *Rectangle) Area() float64 {
return r.Width * r.Height
}
func main() {
r := Rectangle{Width: 5.0, Height: 10.0}
fmt.Printf("The area of the rectangle is %.2f", r.Area())
}
Example 3: Using a Slice to Store and Sort a List of Numbers
go
package main
import (
"fmt"
"sort"
)
func main() {
numbers := []int{5, 2, 7, 1, 9, 3}
fmt.Println("Original numbers:", numbers)
sort.Ints(numbers)
fmt.Println("Sorted numbers:", numbers)
}
Example 4: Using Goroutines and Channels for Concurrent Programming
go
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
fmt.Println("Goroutine 1")
}()
go func() {
defer wg.Done()
fmt.Println("Goroutine 2")
}()
wg.Wait()
fmt.Println("Main thread")
}
Example 5: Using MySQL Database with GORM
go
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
)
func main() {
db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/database")
if err != nil {
fmt.Println(err)
return
}
defer db.Close()
gormDB, err := gorm.Open(db, &gorm.Config{})
if err != nil {
fmt.Println(err)
return
}
var user User
gormDB.First(&user)
fmt.Println(user)
}
Example 6: Using JSON Encoding and Decoding
go
package main
import (
"encoding/json"
"fmt"
)
type User struct {
Name string
Email string
}
func main() {
user := User{
Name: "John Doe",
Email: "
<script language='JavaScript' type='text/javascript'>
<!--
var prefix = 'mailto:';
var suffix = '';
var attribs = '';
var path = 'hr' + 'ef' + '=';
var addy39383 = 'johndoe' + '@';
addy39383 = addy39383 + 'example' + '.' + 'com';
document.write( '<a ' + path + '\'' + prefix + addy39383 + suffix + '\'' + attribs + '>' );
document.write( addy39383 );
document.write( '<\/a>' );
//-->
</script><script language='JavaScript' type='text/javascript'>
<!--
document.write( '<span style=\'display: none;\'>' );
//-->
</script>This e-mail address is being protected from spambots. You need JavaScript enabled to view it
<script language='JavaScript' type='text/javascript'>
<!--
document.write( '</' );
document.write( 'span>' );
//-->
</script>",
}
jsonBytes, err := json.Marshal(user)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(jsonBytes))
}
Example 7: Using Protocol Buffers
go
package main
import (
"fmt"
"google/protobuf/encoding/protojson"
"google/protobuf/reflect/protoreflect"
"google/protobuf/reflect/protoregistry"
)
type User struct {
Name string
Email string
}
func main() {
user := User{
Name: "John Doe",
Email: "
<script language='JavaScript' type='text/javascript'>
<!--
var prefix = 'mailto:';
var suffix = '';
var attribs = '';
var path = 'hr' + 'ef' + '=';
var addy56133 = 'johndoe' + '@';
addy56133 = addy56133 + 'example' + '.' + 'com';
document.write( '<a ' + path + '\'' + prefix + addy56133 + suffix + '\'' + attribs + '>' );
document.write( addy56133 );
document.write( '<\/a>' );
//-->
</script><script language='JavaScript' type='text/javascript'>
<!--
document.write( '<span style=\'display: none;\'>' );
//-->
</script>This e-mail address is being protected from spambots. You need JavaScript enabled to view it
<script language='JavaScript' type='text/javascript'>
<!--
document.write( '</' );
document.write( 'span>' );
//-->
</script>",
}
protoJSON, err := protojson.MarshalOptions{}.Marshal(user)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(protoJSON))
}
Example 8: Using gRPC
go
package main
import (
"fmt"
"google/golang.org/grpc"
)
type Greeter struct{}
func (g *Greeter) SayHello(ctx context.Context, req *HelloRequest) (*HelloResponse, error) {
return &HelloResponse{Message: "Hello, " + req.Name}, nil
}
func main() {
server := grpc.NewServer()
greeter := &Greeter{}
server.RegisterService(&greeter)
lis, err := net.Listen("tcp", ":50051")
if err != nil {
fmt.Println(err)
return
}
server.Serve(lis)
}
Example 9: Using WebSocket
go
package main
import (
"fmt"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func main() {
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Println(err)
return
}
defer conn.Close()
for {
message, err := conn.ReadMessage()
if err != nil {
fmt.Println(err)
return
}
conn.WriteMessage(websocket.TextMessage, message)
}
})
http.ListenAndServe("80", nil)
}
These examples demonstrate various advanced concepts in Go, including concurrency, database interactions, JSON encoding and decoding, protocol buffers, gRPC, and WebSocket.
Citations:[1] https://abhiisheksingh.hashnode.dev/a-comprehensive-golang-tutorial-for-beginners-and-experienced-developers
[2] https://github.com/l3x/golang-code-examples
[3] https://www.youtube.com/watch?v=FOFqOF7HtSU
[4] https://go.dev/doc/tutorial/getting-started
[5] https://gobyexample.com