<> summary
Conditional statements require the developer to specify one or more conditions
And test whether the condition is true To determine whether to execute the specified statement
And under the condition of false And then execute another statement .
<> grammar
package main func main() { // The first format if Conditional expression { sentence 1 } // The second format if Initialization expression ; Conditional expression {
sentence 1 } // Third format if Initialization expression ; Conditional expression { sentence 1 }else{ sentence 2 } // The fourth format if Initialization expression ; Conditional expression { sentence 1
}else if Initialization expression ; Conditional expression { sentence 2 }else{ sentence 3 } }
Format Rules
1)Go A conditional statement in a language does not need parentheses , But there must be braces in the branch .
2)Go It can be used in language conditional statements := Initialize a variable , But remember , This variable is a local variable , The scope of this variable is only if Within the scope .
3)Go Right in the language if/else Format alignment is very strict , if necessary if/else combination , You need to if The curly brackets at the end of the statement follow else.
Write the code here
4) keyword if and else Left brace after { Must be on the same line as the keyword , If you use else-if structure , The right brace of the preceding code block } Must be with
else-if Keywords on the same line . Both rules are mandatory by the compiler .
Sample code
package main import ( "fmt" "io/ioutil" // Be sure to import the package ) func main() { age := 10
//1. The first expression if if age > 10 { // Other languages have brackets , There are no brackets here , If you add brackets ,go fmt Or will you delete your brackets fmt.
Println("age greater than 10") } //2. The second expression if else if age > 20 { fmt.Println("age greater than 20") }
else { fmt.Println("age less than 20") } //3. The third expression if-else if if age == 20 { fmt.
Println("age be equal to 20") } else if age > 20 { fmt.Println("age greater than 20") } else { fmt.
Println("age less than 20") } //4. The fourth format Initialization expression ; Conditional expression if i := 20; i == 10 { fmt.Println(
"i be equal to 10") } else { fmt.Println("i Not equal to 10") } // read file
ioutil It's a go My own bag ,ReadFile The initial size indicates that the method is public ,nil Indicates whether it is empty , If it is not empty, it means that opening the file failed // Be sure to import io/ioutil
// Must be created in the current directory abc.txt file if response, err := ioutil.ReadFile("abc.txt"); err !=
nil { fmt.Println(err) } else { fmt.Println(string(response)) } }
Technology