My journey to learn GO :Day2
FOR
- GO has only one looping constuct ,the for loop.
- The basic for loop has three components separated by semicolors:
- the init statement;
- the condition expression;
- the post statement
func main(){
sum := 0
for i := 0;/*the init statement*/
i < 10;/*the condition expression*/
i++ /*the post statement*/ {
for j := 0; j < 10; j++{
sum+=i+j
}
}
fmt.Println(sum)
}
- The init and post statements are optional.
func main(){
sum:=0
for ; sum<100; {
sum+=sum
}
fmt.Println(sum)
}
- For in Go's "while".
func main(){
sum:=1
for sum < 10 {// the statement likes the C's while
sum+=sum
}
fmt.Println(sum)
}
IF
- The expression need not be surrounded by the parentheses () but the braces {} are required.
func sqrt(x float64) string {
if x < 0 {
return sqrt(-x)+"i"
}
return fmt.Sprint(math.Sqrt(x))
}
- the if statement can start with short statement to execute before the condition.
func pow(x, n, lim float64) float64 {
if v := math.Pow(x, n); v < lim {//like the for statement
return v
}
return lim
}
- if and else:variables declared inside an if short statement alse available inside any of the else blocks.
func max(x, y int) int {
if sum := 0; x > y {
sum = x
return sum
} else {
sum = y
return sum
}
}
Exercise:
func Sqrt(x float64) float64 {
z := float64(1)
for math.Abs(x-z*z) > 0.00000000001 {
z -= (z*z - x) / (2 * z)
}
return z
}
Switch
- The break statement that is needed at the end of each case is provided automatically in Go.
func main() {
fmt.Print("Go runs on ")
// o s := runtime.GOOS This is okay too!
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
default:
// freebsd, openbsd,
// plan9, windows...
fmt.Printf("%s.\n", os)
}
}
- Switch cases evaluate cases from the top to buttom,stoping when a case succeeds.
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.")
}
}
- Switch without a condition is the same as switch true.
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.")
}
}
Defer
- A defer statement defers the execution of a function until the surrouding function returns.
func main(){
defer fmt.Prinln("world")
fmt.Println("hello")//the function run fast than the defer function
}
- Deferred function calls are pushed onto a stack.When a function returns,its deferred calls are executed in last-in-first-out order.
func main(){
fmt.Println("couting")
for i:=0;i<10;i++{
defer fmt.Pintln(i)
}
fmt.Println("done")
}