# defer、return及赋值顺序

```func getNumber() int {
number := 0
threshold := 10000
// do something and assign value to number
number = 99999
// do something
// ... ...

// check number is valid or not
if number > threshold {
number = threshold
}
return number
}```

```func getNumber() int {
threshold := 10000
number := 0

// check before return
defer func() {
// check number is valid or not
if number > threshold {
number = threshold
}
}()

// do something and assign value to number
number = 99999
// do something
// ... ...

return number
}

func main() {
fmt.Println(getNumber())
}```

main函数里的输出可能有点意外，输出为99999。并没有得到我们预期的结果。那这里的原因是什么呢？其实，return包含了两个步骤：

1. 给返回值赋值；
2. 调用RET返回指令并传入返回值，而RET则会检查defer是否存在，若存在就先逆序插播defer语句，最后RET携带返回值退出函数。

```func getNumber() (number int) {
threshold := 10000

// check before return
defer func() {
// check number is valid or not
if number > threshold {
number = threshold
}
}()

// do something and assign value to number
number = 99999
// do something
// ... ...

return number
}```