#golang #go #programming
If and switch constructs
---------
1. Basic If
2. Basic If with short statement (variable scope)
1. If statement can accommodate a short operative statement along with a conventional conditional statement
2. Short statement variables defined in if, will be accessible only within the scope of if..else construct
3. Basic Switch (break not needed)
Break statement is not needed, as every case will complete the switch construct when it gets executed
Switch statement can test a string,int,character,expressions,statements,etc, whereas in c,c++, it will support only constants that too int,float,char variables
4. Switch with short statement (variable scope)
Similar to If condition, we can include a short statement containing declaration or assignment for any switch test
5. Switch without a condition
-Empty switches should not contain any case statement. Default is the only permissible block inside empty switch
On seeing an empty switch the compiler will understand it as "switch true" and permists the execution to the default statment
-----------------------
Code
------
conditiondemo.go
------------------
package main
import "fmt"
func main(){
if a:=20; a==5 { //Declare or assign using short statement and condition
fmt.Printf("Value of a is %d and it is equal to 5\n",a)
} else {
fmt.Printf( "Value of a is %d and it is not equal to 5\n",a)
}
// fmt.Println(a) can't access the variable 'a' assigned in 'if' short statement outside the if..else construct
}
switchdemo.go
-------------
package main
import "fmt"
func main(){
switch name:="ghi";name { //Short statement with testing the variable "name"
case "abc":
fmt.Println("First three alphabets")
case "def":
fmt.Println("Second set of three alphabets")
default:
fmt.Println("Not belongs to first and second set of three alphabets")
}
switch { //Empty switch statement without any test variable - implicitly go will consider this empty switch as "switch true"
default :
fmt.Println("Empty switch default block")
}
}
Смотрите видео Go (golang) Tutorials - If and Switch Constructs онлайн, длительностью часов минут секунд в хорошем качестве, которое загружено на канал Ambasoft Java 16 Март 2018. Делитесь ссылкой на видео в социальных сетях, чтобы ваши подписчики и друзья так же посмотрели это видео. Данный видеоклип посмотрели 152 раз и оно понравилось 5 посетителям.