One place for hosting & domains

      Switch

      How To Write Switch Statements in Go


      Introduction

      Conditional statements give programmers the ability to direct their programs to take some action if a condition is true and another action if the condition is false. Frequently, we want to compare some variable against multiple possible values, taking different actions in each circumstance. It’s possible to make this work using if statements alone. Writing software, however, is not only about making things work but also communicating your intention to your future self and other developers. switch is an alternative conditional statement useful for communicating actions taken by your Go programs when presented with different options.

      Everything we can write with the switch statement can also be written with if statements. In this tutorial, we’ll look at a few examples of what the switch statement can do, the if statements it replaces, and where it’s most appropriately applied.

      Structure of Switch Statements

      Switch is commonly used to describe the actions taken by a program when a variable is assigned specific values. The following example demonstrates how we would accomplish this using if statements:

      package main
      
      import "fmt"
      
      func main() {
          flavors := []string{"chocolate", "vanilla", "strawberry", "banana"}
      
          for _, flav := range flavors {
              if flav == "strawberry" {
                  fmt.Println(flav, "is my favorite!")
                  continue
              }
      
              if flav == "vanilla" {
                  fmt.Println(flav, "is great!")
                  continue
              }
      
              if flav == "chocolate" {
                  fmt.Println(flav, "is great!")
                  continue
              }
      
              fmt.Println("I've never tried", flav, "before")
          }
      }
      

      This will generate the following output:

      Output

      chocolate is great! vanilla is great! strawberry is my favorite! I've never tried banana before

      Within main, we define a slice of ice-cream flavors. We then use a for loop to iterate through them. We use three if statements to print out different messages indicating preferences for different ice-cream flavors. Each if statement must use the continue statement to stop execution of the for loop so that the default message at the end is not printed for the preferred ice-cream flavors.

      As we add new ice-cream preferences, we have to keep adding if statements to handle the new cases. Duplicated messages, as in the case of "vanilla" and "chocolate", must have duplicated if statements. To future readers of our code (ourselves included), the repetitive nature of the if statements obscures the important part of what they are doing—comparing the variable against multiple values and taking different actions. Also, our fallback message is set apart from the conditionals, making it appear unrelated. The switch statement can help us organize this logic better.

      The switch statement begins with the switch keyword and is followed, in its most basic form, with some variable to perform comparisons against. This is followed by a pair of curly braces ({}) where multiple case clauses can appear. Case clauses describe the actions your Go program should take when the variable provided to the switch statement equals the value referenced by the case clause. The following example converts the previous example to use a switch instead of multiple if statements:

      package main
      
      import "fmt"
      
      func main() {
          flavors := []string{"chocolate", "vanilla", "strawberry", "banana"}
      
          for _, flav := range flavors {
              switch flav {
              case "strawberry":
                  fmt.Println(flav, "is my favorite!")
              case "vanilla", "chocolate":
                  fmt.Println(flav, "is great!")
              default:
                  fmt.Println("I've never tried", flav, "before")
              }
          }
      }
      

      The output is the same as before:

      Output

      chocolate is great! vanilla is great! strawberry is my favorite! I've never tried banana before

      We’ve once again defined a slice of ice-cream flavors in main and used the range statement to iterate over each flavor. This time, however, we’ve used a switch statement that will examine the flav variable. We use two case clauses to indicate preferences. We no longer need continue statements as only one case clause will be executed by the switch statement. We’re also able to combine the duplicated logic of the "chocolate" and "vanilla" conditionals by separating each with a comma in the declaration of the case clause. The default clause serves as our catch-all clause. It will run for any flavors that we haven’t accounted for in the body of the switch statement. In this case, "banana" will cause default to execute, printing the message I've never tried banana before.

      This simplified form of switch statements addresses the most common use for them: comparing a variable against multiple alternatives. It also provides conveniences for us where we want to take the same action for multiple different values and some other action when none of the listed conditions are met by using the provided default keyword.

      When this simplified form of switch proves too limiting, we can use a more general form of switch statement.

      General Switch Statements

      switch statements are useful for grouping collections of more complicated conditionals to show that they are somehow related. This is most commonly used when comparing some variable against a range of values, rather than specific values as in the earlier example. The following example implements a guessing game using if statements that could benefit from a switch statement:

      package main
      
      import (
          "fmt"
          "math/rand"
          "time"
      )
      
      func main() {
          rand.Seed(time.Now().UnixNano())
          target := rand.Intn(100)
      
          for {
              var guess int
              fmt.Print("Enter a guess: ")
              _, err := fmt.Scanf("%d", &guess)
              if err != nil {
                  fmt.Println("Invalid guess: err:", err)
                  continue
              }
      
              if guess > target {
                  fmt.Println("Too high!")
                  continue
              }
      
              if guess < target {
                  fmt.Println("Too low!")
                  continue
              }
      
              fmt.Println("You win!")
              break
          }
      }
      

      The output will vary depending on the random number selected and how well you play the game. Here is the output from one example session:

      Output

      Enter a guess: 10 Too low! Enter a guess: 15 Too low! Enter a guess: 18 Too high! Enter a guess: 17 You win!

      Our guessing game needs a random number to compare guesses against, so we use the rand.Intn function from the math/rand package. To make sure we get different values for target each time we play the game, we use rand.Seed to randomize the random number generator based on the current time. The argument 100 to rand.Intn will give us a number in the range 0–100. We then use a for loop to begin collecting guesses from the player.

      The fmt.Scanf function gives us a means to read user input into a variable of our choosing. It takes a format string verb that converts the user’s input into the type we expect. %d here means we expect an int, and we pass the address of the guess variable so that fmt.Scanf is able to set that variable. After handling any parsing errors we then use two if statements to compare the user’s guess to the target value. The string that they return, along with bool, controls the message displayed to the player and whether the game will exit.

      These if statements obscure the fact that the range of values that the variable is being compared against are all related in some way. It can also be difficult, at a glance, to tell if we missed some part of the range. The next example refactors the previous example to use a switch statement instead:

      package main
      
      import (
          "fmt"
          "math/rand"
      )
      
      func main() {
          target := rand.Intn(100)
      
          for {
              var guess int
              fmt.Print("Enter a guess: ")
              _, err := fmt.Scanf("%d", &guess)
              if err != nil {
                  fmt.Println("Invalid guess: err:", err)
                  continue
              }
      
              switch {
              case guess > target:
                  fmt.Println("Too high!")
              case guess < target:
                  fmt.Println("Too low!")
              default:
                  fmt.Println("You win!")
                  return
              }
          }
      }
      

      This will generate output similar to the following:

      Output

      Enter a guess: 25 Too low! Enter a guess: 28 Too high! Enter a guess: 27 You win!

      In this version of the guessing game, we’ve replaced the block of if statements with a switch statement. We omit the expression argument to switch because we are only interested in using switch to collect conditionals together. Each case clause contains a different expression comparing guess against target. Similar to the first time we replaced if statements with switch, we no longer need continue statements since only one case clause will be executed. Finally, the default clause handles the case where guess == target since we have covered all other possible values with the other two case clauses.

      In the examples that we’ve seen so far, exactly one case statement will be executed. Occasionally, you may wish to combine the behaviors of multiple case clauses. switch statements provide another keyword for achieving this behavior.

      Fallthrough

      Sometimes you will want to reuse the code that another case clause contains. In these cases, it’s possible to ask Go to run the body of the next case clause listed using the fallthrough keyword. This next example modifies our earlier ice cream flavor example to more accurately reflect our enthusiasm for strawberry ice cream:

      package main
      
      import "fmt"
      
      func main() {
          flavors := []string{"chocolate", "vanilla", "strawberry", "banana"}
      
          for _, flav := range flavors {
              switch flav {
              case "strawberry":
                  fmt.Println(flav, "is my favorite!")
                  fallthrough
              case "vanilla", "chocolate":
                  fmt.Println(flav, "is great!")
              default:
                  fmt.Println("I've never tried", flav, "before")
              }
          }
      }
      

      We will see this output:

      Output

      chocolate is great! vanilla is great! strawberry is my favorite! strawberry is great! I've never tried banana before

      As we’ve seen previously, we define a slice of string to represent flavors and iterate through this using a for loop. The switch statement here is identical to the one we’ve seen before, but with the addition of the fallthrough keyword at the end of the case clause for "strawberry". This will cause Go to run the body of case "strawberry":, first printing out the string strawberry is my favorite!. When it encounters fallthrough it will run the body of the next case clause. This will cause the body of case "vanilla", "chocolate": to run, printing strawberry is great!.

      The fallthrough keyword is not used often by Go developers. Usually, the code reuse realized by using fallthrough can be better obtained by defining a function with the common code. For these reasons, using fallthrough is generally discouraged.

      Conclusion

      switch statements help us convey to other developers reading our code that a set of comparisons are somehow related to each other. They make it much easier to add different behavior when a new case is added in the future and make it possible to ensure that anything we forgot is handled properly as well with default clauses. The next time you find yourself writing multiple if statements that all involve the same variable, try rewriting it with a switch statement—you’ll find it easier to rework when it comes time to consider some other alternative value.

      If you’d like to learn more about the Go programming language, check out the entire How To Code in Go series.



      Source link

      Should I Switch Web Hosts? How to Know When It’s Time to Migrate Your Site


      When it comes to starting a website, web hosting is one of the most crucial yet most confusing aspects to tackle. With dozens of providers on the market, it can be hard to cut through the noise and figure out which one offers the best plan for you.

      Fortunately, several signs will make it clear when it’s time to move to a new host. While they’re not so pleasant to deal with in the moment, these issues may lead you to a better service provider that can help you boost your site’s success.

      In this post, we’ll discuss these signs and how to spot them on your website. Then we’ll explain how to migrate your site to a new web hosting platform. Let’s get started!

      Have a website? We’ll move it for you!

      Migrating to a new web hosting provider can be a pain. We’ll move your existing site within 48 hours without any interruption in service. Included FREE with any DreamPress plan.

      How to Know When It’s Time to Migrate (6 Tell-Tale Signs)

      It’s possible you’ve been experiencing problems with your website for a while now without really knowing why. In some cases, it may be that your web hosting provider isn’t a good fit for your website. These six signs will let you know it’s time to switch web hosts.

      1. You’re Experiencing More Downtime Than Usual

      Any time your website is unavailable to users, it’s considered ‘down.’ Even if your site is only unavailable for seconds at a time, it could cause serious problems. For starters, downtime makes your website appear unreliable and low-quality to both users and search engines.

      If your site is experiencing frequent outages, your users will come to find they can’t rely on it to be available when needed. The Google algorithm will account for this, and your search engine rankings will fall as well, hurting your site’s visibility.

      Plus, if your site generates revenue, you’ll be missing out on income every time your site has an outage. If your site is down often or for long periods of time, you could be losing hundreds or even thousands of dollars. When you’re running an online store, uptime truly affects your bottom line.

      Web hosting is one of the most common causes of website downtime, as there are many ways in which your server can impact your site’s availability, including:

      • The quality and reliability of your hosting equipment
      • The type of server your website is on, as shared servers tend to become overloaded more quickly than other types of servers.
      • Your host’s security features, since malicious attacks can lead to downtime.

      So, if you keep finding your website is down, there’s a fair chance your host may have something to do with it. Moving to a more reliable server is the best thing for your site in a situation like this.

      2. Your Website’s Loading Speed Is Slow

      Site speed is also key to Search Engine Optimization (SEO), users’ opinions of your site, and your conversion rate. It’s wise to test your site’s speed every once in a while using tools such as Google PageSpeed Insights and Pingdom to make sure your loading times are staying low and to fix any performance issues.

      Pingdom’s results screen.

      While a crowded server can certainly slow your loading times, your server’s location also plays a role in how fast your site delivers information to visitors. Servers located far away from end users aren’t able to serve them content as quickly.

      An easy way to determine if this is the case for your website is to use Pingdom to test your site speed from a variety of locations. If your site loads quickly from some places yet takes a long time to load in others, you’ll know server location is causing speed issues for users in those regions.

      If your host only has servers in one location and doesn’t offer a Content Delivery Network (CDN), it’s almost guaranteed that some portion of your users will experience less-than-ideal site speed. It may be worth looking into hosts with more or different locations, or ones offering a CDN.

      3. Customer Service Isn’t Helpful

      A solid relationship with your web host is priceless. For starters, there are going to be times when server-related errors occur on your site. In these instances, you’ll need to be able to get ahold of your host quickly to resolve the issue and get your site back up. Plus, you may sometimes have questions about billing or other account details.

      However, the best hosts also offer support in other areas of website management. For example, many hosts provide troubleshooting guidance for different types of errors on your website or support for platforms such as WordPress.

      If your host is difficult to get in touch with, provides inadequate solutions, or doesn’t offer support in areas directly related to your hosting account, consider switching to a new provider. While you may be able to get by without quality customer support, at some point, you’ll have to reach someone for help with a server-related problem, so you’ll want a reliable team at your back.

      4. You Need More Space Than Your Current Provider Can Offer

      Most websites start small and grow over time. Your current host may have been a great fit when you were first launching your site, but if your traffic levels have increased significantly, this may no longer be the case.

      As your site accumulates more recurring users, you’ll need a server that can handle more traffic as well as more and larger website files. Moving from shared hosting to a dedicated server can help, but switching hosts can often provide a greater benefit.

      Some providers specialize in shared or Virtual Private Network (VPN) hosting and may not offer dedicated servers. As such, if your site continues to grow, you’ll need a dedicated web hosting service at some point — so a switch may be inevitable.

      Other hosts may have dedicated servers available, but still not offer as much storage as you need. Ultimately, you’ll want to compare plans between companies to see which one offers the most space for the best price.

      5. It’s Getting Too Expensive to Stay With Your Current Host

      Web hosting is a recurring expense. It’s also sometimes the largest expense associated with running a website, especially for WordPress users working with a free Content Management System (CMS) and mainly free plugins and themes.

      It’s true that you often get what you pay for with hosting. However, there are also times when an expensive plan isn’t necessary. If your site is still small and not using the amount of server space you’re paying for, or if your current hosting plan comes with several features you never touch, you’re probably paying too much.

      There’s no sense in breaking the bank to host your website when there are plenty of affordable options available. For example, we offer high-quality managed WordPress hosting plans for as low as $16.95 per month.

      If you’re shelling out more money for web hosting than what your website brings in, you might want to consider downsizing or switching hosts to stay within your budget. Plus, it never hurts to pocket a little extra cash each month.

      6. Server Security Is Sub-Par

      As we mentioned earlier in this post, hosts are responsible for securing their servers. Not every provider is as diligent as they should be when it comes to security, and hackers will sometimes exploit weaknesses in your server to gain access to your site.

      This can be detrimental to your website for multiple reasons, including:

      • The loss of parts or all of your site due to a malicious attack that destroys key files and data.
      • Compromised user data, including sensitive information such as private records and credit card details.
      • Decreased credibility, as users will see your site as less reliable if it’s hacked.

      Investing in secure hosting is a smart move. Even if you have to pay a little extra or go through the trouble of migrating to a new host, you’ll save yourself a lot of trouble down the line.

      Some security features you may want to keep an eye out for are Secure Sockets Layer (SSL) certificates, malware scanning, and server firewalls. Of course, no matter how secure your server is, you should always follow security best practices for your site itself, too.

      How to Migrate Your Website to a New Hosting Provider

      If you’ve considered the signs mentioned above and determined you should switch hosting providers, you’ll need to migrate your website. This requires you to copy all your website’s files and move them to your new hosting account.

      Typically, the migration process is pretty involved. You’ll have to contact your current host, back up your site files, then use Secure File Transfer Protocol (SFTP) and a client such as FileZilla to connect to your new server and upload your files. You’ll also want to consider transferring your domain since there are benefits to keeping your domain registration and web hosting under one roof.

      As you might imagine, there are a lot of things that could go wrong during this process. For example, corrupted backups are always a possibility, and using SFTP still poses a risk to your site’s files as you could mistakenly delete some or all of them (we recommend users always have a recent backup of their site on hand).

      These things considered, it’s helpful if you can get an expert on board to migrate your site for you. Fortunately, if you’re a WordPress user and have decided to switch to DreamHost, our managed WordPress hosting plans include free website migration services.

      DreamHost’s WordPress migration services.

      We’ll handle moving your site at no extra cost. If you’d prefer one of our shared hosting plans or have a website built without using WordPress, never fear. You can still take advantage of our migration service for just $99.

      Our migration experts will get your site moved to your new hosting account within 48 hours of your request. You’ll also avoid downtime altogether, so you don’t have to worry about negatively impacting your users’ experience while you move your site and get acquainted with the DreamHost control panel.

      Looking for a New Hosting Provider?

      We make moving easy. Our hassle-free, high-performance WordPress hosting includes a FREE professional migration service ($99 savings)!

      Switching Web Hosts

      Hosting can be one of the most confusing aspects of owning a website. With so many options to choose from, it can be difficult to know if your web hosting provider is the best one available for your needs.

      If you’ve noticed these issues on your website and have decided it’s time for a change, consider checking out our DreamPress hosting plans. Our managed WordPress hosting service will provide you with the speed, support, and security your WordPress site needs. Plus, you’ll be able to use our site migration services for free.



      Source link