Programing/Go
if 문(11)
the best infra
2025. 1. 11. 20:05
* if 문?
- if문은 제어문이자 조건문이다. 조건에 따라서 결과를 반환한다.
- 조건은 true인 경우에만 { } 안에 내용을 반환한다.
- else로 마지막 조건문을 선언할 수 있고 else if로 질질 조건문을 늘려 갈 수 있다.
* if 예제 - 1
- true 인 조건이 나올 때 까지 계속 조건문을 실행한다.
package main
import "fmt"
func main() {
temp := 33
// 조건 부분 (temp > 28) 은 bool 타입으로 결과를 반환한다.
if temp > 28 {
fmt.Println("에어컨을 킨다~")
} else if temp <= 3 {
fmt.Println("히터를 킨다~")
} else if temp <= 18 {
fmt.Println("나가자!")
} else {
fmt.Println("덥다 :(")
}
}
- 실행한 결과 값
* if 예제 - 2
package main
import "fmt"
func main() {
var age = 22
if age >= 10 && age <= 15 {
fmt.Println("You are young")
} else if age > 30 || age < 20 {
fmt.Println("You are not 20s")
} else {
fmt.Println("Best age")
}
}
- 출력 결과 값
* 예제 - 3
package main
import "fmt"
var cnt int = 0 // 전역 변수 선언 > main 패키지에 속해 있음
func IncreaseAndReturn() int {
fmt.Println("IncreaseAndReturn()", cnt)
cnt++
return cnt
}
// false가 이미 들어가 있어서 false를 반환
func main () {
if false && IncreaseAndReturn() < 5 {
fmt.Println("1 증가")
}
}
- 결과 값은 false 이기에 나오지 않아야 한다.
* 중첩 if 문
package main
import "fmt"
func HasRichFried() bool {
return true
}
func GetFirendsCount() int {
return 3
}
func main() {
price := 35000
if price >= 50000 {
if HasRichFried() {
fmt.Println("앗 신발끈이 풀렸네")
} else {
fmt.Println("나눠내자")
}
} else if price >= 30000 {
if GetFirendsCount() > 3 {
fmt.Println("앗 신발끈이 풀렸네")
} else {
fmt.Println("사람도 없는데 나눠 내자")
}
} else {
fmt.Println(" 오늘은 내가 쏜다! ")
}
}
- 결과 값 출력
* 초기문; 조건문
- 초기문은 값을 초기화 할 때 사용. 초기문; 조건문으로 사용이 된다.
if filename, success := UploadFile(); success {
fmt.Println("Upload success", filename)
} else {
fmt.Println("Failed to upload")
}