Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Go – Third Edition

You're reading from   Mastering Go – Third Edition Harness the power of Go to build professional utilities and concurrent servers and services

Arrow left icon
Product type Paperback
Published in Aug 2021
Publisher Packt
ISBN-13 9781801079310
Length 682 pages
Edition 3rd Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Mihalis Tsoukalos Mihalis Tsoukalos
Author Profile Icon Mihalis Tsoukalos
Mihalis Tsoukalos
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

Preface 1. A Quick Introduction to Go 2. Basic Go Data Types FREE CHAPTER 3. Composite Data Types 4. Reflection and Interfaces 5. Go Packages and Functions 6. Telling a UNIX System What to Do 7. Go Concurrency 8. Building Web Services 9. Working with TCP/IP and WebSocket 10. Working with REST APIs 11. Code Testing and Profiling 12. Working with gRPC 13. Go Generics 14. Other Books You May Enjoy
15. Index
Appendix A – Go Garbage Collector

Reflection versus generics

In this section, we develop a utility that prints the elements of a slice in two ways: first, using reflection, and second, using generics.

The code of reflection.go is as follows:

package main
import (
    "fmt"
    "reflect"
)
func PrintReflection(s interface{}) {
    fmt.Println("** Reflection")
    val := reflect.ValueOf(s)
    if val.Kind() != reflect.Slice {
        return
    }
    for i := 0; i < val.Len(); i++ {
        fmt.Print(val.Index(i).Interface(), " ")
    }
    fmt.Println()
}

Internally, the PrintReflection() function works with slices only. However, as we cannot express that in the function signature, we need to accept an empty interface parameter. Additionally, we have to write more code to get the desired output.

In more detail, first, we need to make sure that we are processing a slice (reflect.Slice) and second, we have to print the slice elements using a for loop, which...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image