File tree Expand file tree Collapse file tree 1 file changed +73
-0
lines changed
Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Original file line number Diff line number Diff line change @@ -1782,6 +1782,79 @@ func main() {
17821782
17831783< /details>
17841784
1785+ < details>
1786+ < summary> switch 语句< /summary>
1787+
1788+ ` ` ` go
1789+ package main
1790+ import (
1791+ " fmt"
1792+ " runtime"
1793+ )
1794+ func main () {
1795+ fmt.Print(" Go runs on " )
1796+ switch os := runtime.GOOS; os {
1797+ case " darwin" :
1798+ fmt.Println(" OS X." )
1799+ case " linux" :
1800+ fmt.Println(" Linux." )
1801+ default:
1802+ // freebsd, openbsd,
1803+ // plan9, windows...
1804+ fmt.Printf(" %s." , os)
1805+ }
1806+ }
1807+ ` ` `
1808+
1809+ 在 if 的便捷语句定义的变量同样可以在任何对应的 else 块中使用。
1810+
1811+ ** switch 的执行顺序:** 条件从上到下的执行,当匹配成功的时候停止。
1812+
1813+ ` ` ` go
1814+ package main
1815+ import (
1816+ " fmt"
1817+ " time"
1818+ )
1819+ func main () {
1820+ fmt.Println(" When's Saturday?" )
1821+ today := time.Now().Weekday ()
1822+ switch time.Saturday {
1823+ case today + 0:
1824+ fmt.Println(" Today." )
1825+ case today + 1:
1826+ fmt.Println(" Tomorrow." )
1827+ case today + 2:
1828+ fmt.Println(" In two days." )
1829+ default:
1830+ fmt.Println(" Too far away." )
1831+ }
1832+ }
1833+ ` ` `
1834+
1835+ ** 没有条件的 switch 同 switch true 一样。**
1836+
1837+ ` ` ` go
1838+ package main
1839+ import (
1840+ " fmt"
1841+ " time"
1842+ )
1843+ func main () {
1844+ t := time.Now ()
1845+ switch {
1846+ case t.Hour () < 12:
1847+ fmt.Println(" Good morning!" )
1848+ case t.Hour () < 17:
1849+ fmt.Println(" Good afternoon." )
1850+ default:
1851+ fmt.Println(" Good evening." )
1852+ }
1853+ }
1854+ ` ` `
1855+
1856+ < /details>
1857+
17851858# # 资源导航
17861859
17871860< details>
You can’t perform that action at this time.
0 commit comments