package main
import (
"fmt"
)
/*
封装人,属性包括姓名,年龄,身高,体重,颜值,资产,性别,性取向
给人封装结婚方法,参数是潜在的结婚对象
①如果对方的性取向有问题,panic
②如果对方的颜值过低,返回错误
③否则返回满意程度
*/
//性别枚举
type Gander int
func (g Gander)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 (bse *BadSpouseError)String()string{
return bse.why
}
type Human struct {
Name string
Age int
Height int
Weight int
Rmb int
//自己的颜值
Looking int
//结婚对象的颜值
TargetLooking int
//自己的性别
Sex Gander
//结婚对象的性别
TargetSex Gander
}
//h *Human 自己结婚,o *Human:结婚对象,happiness int默认是0
func (h *Human)Marry(o *Human) (happiness int,err error){
//如果对方的性取向有问题,panic
if o.Sex != h.TargetSex{
panic(&BadSpouseError{"性别不符合要求"})
}
//如果对方的颜值过低,返回错误
if o.Looking < h.TargetLooking{
//err = errors.New("颜值过低")
err = &BadSpouseError{"颜值过低"}
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 Gander) *Human{
h := new(Human)
h.Name = name
h.Age = age
h.Height , h.Weight , h.Rmb , h.Looking , h.TargetLooking , h.Sex , h.TargetSex = height , weight , rmb , looking , targetLooking , sex , targetSex
return h
}
func main() {
defer func() {
if err := recover();err!=nil{
fmt.Println(err)
}
}()
cook := NewHuman("库克",60,180,150,1234567890,60,90,Male,Male)
ySister := NewHuman("你妹",20,180,150,50,99,50,Female,Male)
happiness, err := cook.Marry(ySister)
//happiness, err := ySister.Marry(cook)
if err != nil {
fmt.Println("牵手失败,err=",err)
}else{
fmt.Println("牵手成功,幸福指数=",happiness)
}
}