【Go】综合用例:异常处理

package main

import (
	"fmt"
)

type Gender int

func (g Gender)String() string {
	return []string{"Male","Female","Bisexual"}[g]
}

//性别枚举
const (
	male = iota
	Female
	Bisexual
)

type BadSpouseError struct {
	why string
}

func (bse *BadSpouseError)Error() string {
	return bse.why
}
func creatBadSpouseError(o *Human_91) *BadSpouseError {
	bse := new(BadSpouseError)
	if o.Rmb<1e6{
		bse.why="太穷"
	}else if o.Weight>200{
		bse.why="太胖"
	}else if o.Age>50{
		bse.why="太老"
	}else{
		return nil
	}
	return bse
}
type Human_91 struct {
	Name string
	Age int
	Height int
	Weight int
	Looking int
	TargetLooking int
	Rmb int
	//自己的性别
	Sex Gender
	//性取向
	TargetSex Gender


}

func (h *Human_91)Marry(o *Human_91) (happiness int,err error) {

	if o.Sex != h.TargetSex{
		panic(&BadSpouseError{"性别不符合要求!"})
	}

	if err := creatBadSpouseError(o);err!=nil{
		return
	}

	happiness = o.Height*o.Rmb*o.Looking/o.Weight/o.Age
	return
}

func NewHuman(name string,age,height,weight,rmb,looking,targetLooking int,sex, targetSex Gender) *Human_91 {

	human_1:= new(Human_91)
	human_1.Name = name
	human_1.Age,human_1.Weight,human_1.Rmb,human_1.Looking,human_1.TargetLooking,human_1.Sex,human_1.TargetSex = age,weight,rmb,looking,targetLooking,sex,targetSex
	human_1.Height=height
	return human_1
}

func main() {
	defer func() {
		if err := recover();err!=nil{
			fmt.Println(err)
		}
	}()
	cook := NewHuman("库克", 60, 180, 150, 1889, 60, 80, male, male)
	gang := NewHuman("刚刚", 20, 150, 150, 17, 90, 90, male, Female)
	happiness, err := gang.Marry(cook)
	if err != nil{
		fmt.Println("牵手失败!err=",err)
	}else{
		fmt.Println("牵手成功,幸福指数=",happiness)
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

ReganYue

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

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

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

打赏作者

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

抵扣说明:

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

余额充值