Go Learning notes: Switch statements

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

When the condition determines too many branches, we use the switch statement to optimize the logic.

package mainimport  "FMT" import  "Time" Func main ()  {    //  The base switch usage     i := 2    fmt. Print ("write ", i,  " as ")     switch i {     case 1:        fmt. Println ("one")     case 2:        fmt. Println ("    case 3:        fmt"). Println ("three")     }    //  you can use commas to separate multiple conditions in a case. You can also use the default statement,    //  to execute the logical block specified by default when none of the above cases are satisfied.     switch time. Now (). Weekday ()  {    case time. Saturday, time. Sunday:        fmt. Println ("It ' s the weekend")     default:&nbSp;       fmt. Println ("It ' S a weekday")     }    //  when switch is not followed by an expression, function and If/else are the same, here we     //  can also see that the expression after the case is not necessarily a constant.     t := time. Now ()     switch {    case t.hour ()  < 12:         fmt. Println ("It ' S before noon")     default:         fmt. Println ("It ' S after noon")     }}

The output result is

Write 2 as Twoit ' s a weekdayit ' s before noon


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.