Go语言——随机数 异常处理

5

Go语言——随机数 异常处理

author: histonevon@zohomail.com

date: 2020/08/04

1.随机数

 // rand project main.go
 package main
 ​
 import (
     "fmt"
     "math/rand" //随机数
     "time"      //时间
 )
 ​
 func main() {
     rand.Seed(time.Now().Unix()) //秒级unix时间
     // n := rand.Intn(10)           //十以内的随机整数,0-9
     // switch {
     //或者这么写
     switch n := rand.Intn(10); true { //先判断分子条件表达式是否为真,一般默认为真,true可以省略
     case n > 0: //可以带表达式
         fmt.Println(n, ">0")
     case n < 0:
         fmt.Println(n, "<0")
     default:
         fmt.Println(n, "==0")
     }
 }
 ​

rand

  • 需要import的包:"math/rand"//随机数 "time"//时间

  • rand.Intn(10):十以内的整数(自定义)

  • rand.Seed(time.Now().Unix()):种种子,使用秒级Unix时间

2.异常处理

 // panicRecover project main.go
 package main
 ​
 import (
     "fmt"
 )
 ​
 func main() {
     defer func() { //defer语句保证最后一定运行
         err := recover() //恢复语句
         if err != nil { //即null
             fmt.Println("异常,原因是:", err)
         } else {
             fmt.Println("正常退出")
         }
     }()
     f(100) //参数合法
     f(101) //参数非法
 }
 ​
 func f(x int) {
     if x > 100 {
         panic("参数越界")
     } else {
         fmt.Println("函数成功调用")
     }
 }
 ​

panicRecover