go练习篇(1)

//结构体
//go语言没有类,可把结构体当作类
type student struct {
	id int
	name string
}
//传入的函数需要声明 , 且需要声明返回值类型
func fun(xx,yy,zz int ) (res int){
	res =xx+yy+zz
	return res
}
//字典
func mapp()  {
	students_map := make(map[string] student)
	a:=0
	for a<3{
		var stu student
		stu.id=a
		stu.name="li"
		students_map["1"]=stu
		a+=1
	}
	value , ok := students_map["1"]
	//ok : true or false
	if ok {
		fmt.Print(ok,value)
	}
}
//选择,开关函数
func switchh(){
	var s int
	for a:=0;a<5;a++{
		fmt.Print("请输入")
		fmt.Scan(&s)
		switch s {
		case 1:
			fmt.Println(1)
		case 2:
			fmt.Println(2)
		case 3:
			fmt.Println(3)
		default:
			fmt.Println("other")
		}
	}
}
//循环
//break loop ,goto loop
func looop(){
	for j:=0;j<5;j++{
		fmt.Println(j)
		if j==2{
			j=3
			continue
		}
	}
}
//列表储存结构体,学生成绩管理系统为例
func studentttt(id int ,name string ) *student{
	return & student{id:id,name:name}
}

func add_student() {
	lis :=make([]student,0)
	lis=append(lis, *studentttt(1,"lcx"))
	lis=append(lis, *studentttt(1,"lcxxxx"))
	for a:=0;a<len(lis);a++{
		fmt.Println(lis[a])
	}
}
//不定参数
func manyparam(args ...interface{}){
	for a,b := range args {
		//a:索引 b值
		fmt.Println(a,b)
	}
}

func param_() {
	//manyparam(50,23)
	manyparam(1,"cx",2.8)
}
//打印类型的两种方法
func typee() {
	fmt.Println(reflect.TypeOf(1 ))
	fmt.Printf("%T",1)
}
//int强转string
func conver()  {
	str := strconv.Itoa(10)
	fmt.Println(reflect.TypeOf(str))
}
//匿名函数,闭包(保护变量)
func closure() {
	j:=10
	f := func(){
		i:=5
		fmt.Println(j,i)
		}
	f()
	j*=2
	f()
}
//异常处理
//defer and recover 捕获panic恐慌
func test_exception(x int) {
	//设置recover,recover只能放在defer后面使用
	defer func() {
		//recover() //可以打印panic的错误信息
		//fmt.Println(recover())
		if err := recover(); err != nil { //产生了panic异常
			fmt.Println(err)
		}

	}() //别忘了(), 调用此匿名函数

	var a [10]int
	a[x] = 111 //当x为20时候,导致数组越界,产生一个panic,导致程序崩溃
}

func main() {
	test_exception(20) //当值是1的时候,就不会越界,值是20的时候,就会越界报错。
}

你可能感兴趣的:(goland,从入门到实战,goland)