03-Go语言语法基础(二)

1. 条件查询

1.1 if

  • if的条件里不需要括号
  • if的条件里可以赋值
  • if的提哦啊见里赋值的变量作用域就在这个if语句里
if contents, err := ioutil.ReadFile(filename); err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%s\n", contents)
	}

1.2 switch

  • switch会自动break,除非使用fallthrough
  • switch后可以没有表达式
switch {
	case score < 0 || score > 100:
		panic(fmt.Sprintf(
			"Wrong score: %d", score))
	case score < 60:
		g = "F"
	case score < 80:
		g = "C"
	case score < 90:
		g = "B"
	case score <= 100:
		g = "A"
	}

2. 循环

2.1 for

  • for的条件里不需要括号
  • for的条件里可以省略初始条件,结束条件、递增表达式
//省略初始条件,相当于while
for ; n > 0; n /= 2 {
	lsb := n % 2
	result = strconv.Itoa(lsb) + result
}

//省略初始条件与递增条件,相当于while
for scanner.Scan() {
	fmt.Println(scanner.Text())
}

//无限循环
for {
	fmt.Println("abc")
}

3. 函数

  • 函数可以返回多个值
func div(a, b int) (int int) {
	return a / b, a % b
}
  • 函数返回多个值时可以起名字
  • 仅用于非常简单的函数
  • 对调用者没有区别
func div(a, b int) (q, r int) {
     q = a / b
     r = a % b
	return  
}
  • 函数作参数
func apply(op func(int, int) int, a, b int) int {
	p := reflect.ValueOf(op).Pointer()
	opName := runtime.FuncForPC(p).Name()
	fmt.Printf("Calling function %s with args "+
		"(%d, %d)\n", opName, a, b)

	return op(a, b)
}
  • 可变参数列表
func sum(numbers ...int) int {
	s := 0
	for i := range numbers {
		s += numbers[i]
	}
	return s
}

4. 指针

  • 指针不能运算
  • 值传递,引用传递?go语言只有值传递一种
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

逍遥俊子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值