Go advanced (if for switch, etc)

Source: Internet
Author: User
For

Go has only one loop structure-'for' loop.

BasicforIn addition to '()' (or even cannot be used), loops seem to be the same as those in C or Java, and '{}' is required.

package mainimport "fmt"func main() {sum := 0for i := 0; i < 10; i++ {sum += i}fmt.Println(sum)}

 

For (continued)

As in C or Java, the prefix and Postfix statements can be left empty.

package mainimport "fmt"func main() {sum := 1for ; sum < 1000; {sum += sum}fmt.Println(sum)}

For is the "while" of go"

You can omit the semicolon: cwhileIn go, it is called ''.

package mainimport "fmt"func main() {sum := 1for sum < 1000 {sum += sum}fmt.Println(sum)}
Endless loop

If the loop condition is omitted, the loop will not end, so the endless loop can be expressed in a more concise form.

package mainfunc main() {for {}}

 

If

ifExcept for '()' (or even cannot be used), the statement looks the same as in C or Java, and '{}' is required.

(Familiar ?)

package mainimport ("fmt""math")func sqrt(x float64) string {if x < 0 {return sqrt(-x) + "i"}return fmt.Sprint(math.Sqrt(x))}func main() {fmt.Println(sqrt(2), sqrt(-4))}

 

If convenient statement

AndforSimilarly, the 'if' statement can execute a simple statement before the condition.

The scope of the variables defined by this statement is only inifWithin the specified range.

(At the endreturnStatementvSee .)

package mainimport ("fmt""math")func pow(x, n, lim float64) float64 {if v := math.Pow(x, n); v < lim {return v}return lim}func main() {fmt.Println(pow(3, 2, 10),pow(3, 3, 20),)}

 

If and Else

InifThe variable defined by the convenient statement can also be in any correspondingelseBlock.

Package mainimport ("FMT" "math") func POW (x, N, Lim float64) float64 {If V: = math. pow (x, n); V <Lim {return v} else {FMT. printf ("% G> = % G \ n", V, Lim)} // you cannot use V at the beginning. Return Lim} func main () {FMT. println (POW (3, 2, 10), POW (3, 3, 20 ),)}

 

Switch

A struct ('struct ') is a collection of fields.

UnlessfallthroughStatement ends. Otherwise, the Branch is automatically terminated.

package mainimport ("fmt""runtime")func main() {fmt.Print("Go runs on ")switch os := runtime.GOOS; os {case "darwin":fmt.Println("OS X.")case "linux":fmt.Println("Linux.")default:// freebsd, openbsd,// plan9, windows...fmt.Printf("%s.", os)}}

 

Switch execution sequence

The switch condition is executed from top to bottom and stops when the match is successful.

(For example,

switch i {case 0:case f():}

Wheni==0Does not call 'F '.)

Note: The time in go playground always starts from 23:00:00 UTC, and how to verify this value is left for the reader to complete as an exercise.

package mainimport ("fmt""time")func main() {fmt.Println("When‘s Saturday?")today := time.Now().Weekday()switch time.Saturday {case today + 0:fmt.Println("Today.")case today + 1:fmt.Println("Tomorrow.")case today + 2:fmt.Println("In two days.")default:fmt.Println("Too far away.")}}

 

Conditional Switch

The switch with no conditions is the same as 'Switch true.

This structure allows you to write long if-then-else chains in a clearer form.

package mainimport ("fmt""time")func main() {t := time.Now()switch {case t.Hour() < 12:fmt.Println("Good morning!")case t.Hour() < 17:fmt.Println("Good afternoon.")default:fmt.Println("Good evening.")}}

 

 

 

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.