前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Go】综合用例:异常处理

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

作者头像
Regan Yue
发布2021-09-16 10:43:42
1710
发布2021-09-16 10:43:42
举报
文章被收录于专栏:ReganYue's BlogReganYue's Blog
代码语言:javascript
复制
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)
	}

}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-03-17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档