Go- if-else 结构

版权声明: 本文为 InfoQ 作者【HelloBug】的原创文章。
原文链接:【http://xie.infoq.cn/article/ebea1e9f054a80f78823df30b】。
本文遵守【CC BY-NC-ND】协议,转载请保留原文出处及本版权声明。

Go 学习笔记,学习内容《Go入门指南》
主要介绍以下内容:
使用语法
多个分支结构
判断字符串是否为空
判断操作系统类型
if 包含初始化语句
代码示例可以直接运行
package main
import ( "fmt" "runtime")
var prompt = "Enter a digit, e.g. 3 " + "or %s to quit"
func init() { if runtime.GOOS == "windows" { prompt = fmt.Sprintf(prompt, "Ctrl+Z, Enter") // 格式化字符串,将参数 "Ctrl+Z, Enter" 格式化到 %s 中 } else { prompt = fmt.Sprintf(prompt, "Ctrl+D") } fmt.Println(prompt)}
func main() { var b bool = true if b { // 左花括号和 if 必须在同一行,否则编译错误:unexpected newline, expecting { after if clause fmt.Println("true") //return // if 和 else 中都使用 return 编译不会报错 } else { // else 和 右花括号必须在一行,否则编译错误:syntax error: unexpected else, expecting } fmt.Println("false") //return }
/* 多个分支的 if 语句 1、分支一般不会过多 2、比较可能出现的分支放在前面 3、布尔类型的变量不需要判断 == true这种,因为本身已经是布尔类型 4、if 后面的条件为布尔类型或逻辑类型 */ var num int = 0 if num == 0 { fmt.Println(0) } else if num == 1 { fmt.Println(1) } else { fmt.Println(2) }
/* 判断字符串是否为空 */ str := "" if str == "" { fmt.Println("str is empty") } if len(str) == 0 { fmt.Println("str is empty") }
/* 判断OS类型 使用举例:放在 init 函数中 */ if runtime.GOOS == "windows" { fmt.Println("windows") }
/* if 可以包含初始化语句 */ max := 100 if n1 := 4; n1 < max { // 语句之间必须使用分号分开 fmt.Println("n1(4) < max(100)") }}版权声明: 本文为 InfoQ 作者【HelloBug】的原创文章。
原文链接:【http://xie.infoq.cn/article/ebea1e9f054a80f78823df30b】。
本文遵守【CC BY-NC-ND】协议,转载请保留原文出处及本版权声明。
还未添加个人签名 2018.09.20 加入
还未添加个人简介

促进软件开发及相关领域知识与创新的传播
京公网安备 11010502039052号


评论