Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
The Go Workshop

You're reading from   The Go Workshop Learn to write clean, efficient code and build high-performance applications with Go

Arrow left icon
Product type Paperback
Published in Dec 2019
Publisher Packt
ISBN-13 9781838647940
Length 824 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (6):
Arrow left icon
Sam Hennessy Sam Hennessy
Author Profile Icon Sam Hennessy
Sam Hennessy
Andrew Hayes Andrew Hayes
Author Profile Icon Andrew Hayes
Andrew Hayes
Gobin Sougrakpam Gobin Sougrakpam
Author Profile Icon Gobin Sougrakpam
Gobin Sougrakpam
Jeremy Leasor Jeremy Leasor
Author Profile Icon Jeremy Leasor
Jeremy Leasor
Delio D'Anna Delio D'Anna
Author Profile Icon Delio D'Anna
Delio D'Anna
Dániel Szabó Dániel Szabó
Author Profile Icon Dániel Szabó
Dániel Szabó
+2 more Show less
Arrow right icon
View More author details
Toc

Table of Contents (21) Chapters Close

Preface 1. Variables and Operators FREE CHAPTER 2. Logic and Loops 3. Core Types 4. Complex Types 5. Functions 6. Errors 7. Interfaces 8. Packages 9. Basic Debugging 10. About Time 11. Encoding and Decoding (JSON) 12. Files and Systems 13. SQL and Databases 14. Using the Go HTTP Client 15. HTTP Servers 16. Concurrent Work 17. Using Go Tools 18. Security 19. Special Features Appendix

2. Logic and Loops

Activity 2.01: Implementing FizzBuzz

Solution:

  1. Define package and include import:
    package main
    import (
      "fmt"
      "strconv"
    )
  2. Create the main function:
    func main() {
  3. Create a for loop that starts at 1 and loops until i gets to 100:
      for i := 1; i <= 100; i++{
  4. Initialize a string variable that will hold the output:
      out := ""
  5. Using module logic to check for divisibility, if i is divisible by 3, then add "Fizz" to the out string:
      if i%3 == 0 {
      out += "Fizz"
      }
  6. If divisible by 5, add "Buzz" to the string:
      if i%5 == 0 {
      out += "Buzz"
      }
  7. If neither, convert the number to a string and then add it to the output string:
      if out == "" {
      out = strconv.Itoa(i)
      }
  8. Print the output variable:
      fmt.Println(out)
  9. ...
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 €18.99/month. Cancel anytime