package main import ( "fmt" "math/rand" "os" "time" ) /* @内存数据持久化到文件 ·循环输入一堆人名 ·为每个人创建一个Person对象 ·随机生成其性别、生肖、星座 ·将这些信息写出到《投胎.txt》 */ /*性别常量*/ type Gender int var genders []string = []string{"女","男","娘炮","女汉子","死变态"} const ( Female Gender = iota Male niangpao nvhanzi sibiantai ) /*生肖*/ type Shengxiao int var shengxiaos []string = []string{"鼠","牛","虎","兔子","龙","蛇","马","羊","猴","鸡","狗","猪"} const ( Rat Shengxiao = iota //鼠 Ox //牛 Tiger //虎 Rabbit //兔子 Dragon //龙 Snake //蛇 Horse //马 Goat //羊 Money //猴 Rooster //鸡 Dog //狗 Pig //猪 ) /*星座*/ type Xingzuo int var xingzuos []string = []string{"白羊座","金牛座","双子座","巨蟹座","狮子座","处女座","天秤座","天蝎座","射手座","摩羯座","水瓶座","双鱼座"} const ( Aries Xingzuo = iota //白羊座 Taurus // 金牛座 Gemini // 双子座 Cancer // 巨蟹座 Leo // 狮子座 Virgo // 处女座 Libra //天秤座 Scorpio //天蝎座 Sagittarius //射手座 Capricornus //摩羯座 Aquarius //水瓶座 Pisces //双鱼座 ) type Person struct { Name string Gender Gender Shengxiao Shengxiao Xingzuo Xingzuo } func NewPerson(name string,gender Gender,shengxiao Shengxiao,xingzuo Xingzuo) *Person { person :=new(Person) person.Name = name person.Xingzuo = xingzuo person.Shengxiao = shengxiao person.Gender = gender return person } /* 让Person实现系统的String接口(不要用指针去实现,要用实例去实现) 该接口的String()方法的返回值,会在fmt.printxxx时使用 */ func (p Person)String() string { return fmt.Sprintf("Person{姓名:%s,性别:%s,生肖:%s,星座:%s}",p.Name,genders[p.Gender],shengxiaos[p.Shengxiao],xingzuos[p.Xingzuo]) } func main() { var names = []string{"李元霸", "宇文成都","裴元庆","雄阔海","你妹","山本","一龙"} people := make([]*Person, 0) for _,name := range names{ //随机生成性别,生肖,星座 gender,shengxiao,xingzuo := GetRandomConfig() person := NewPerson(name, gender, shengxiao, xingzuo) people = append(people, person) } for _,p := range people{ fmt.Println(*p) WritePerson2File(`F:BlockChaincodeW2day4投胎.txt`, p) } } /*将人员信息写入指定文件*/ func WritePerson2File(filename string, person *Person) { file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) if err != nil{ fmt.Println("打开文件失败err=",err) return } defer file.Close() file.WriteString(person.String()+" ") fmt.Println("写出成功:",person.Name) } func GetRandomConfig() (gender Gender,shengxiao Shengxiao,xingzuo Xingzuo) { //强制阻塞睡眠1纳秒,以确保时间种子得以更新 time.Sleep(1 * time.Nanosecond) rand := rand.New(rand.NewSource(time.Now().UnixNano())) gender = Gender(rand.Intn(5)) shengxiao = Shengxiao(rand.Intn(12)) xingzuo = Xingzuo(rand.Intn(12)) return }
输出:
Person{姓名:李元霸,性别:男,生肖:羊,星座:摩羯座} 写出成功: 李元霸 Person{姓名:宇文成都,性别:死变态,生肖:狗,星座:金牛座} 写出成功: 宇文成都 Person{姓名:裴元庆,性别:女汉子,生肖:鸡,星座:水瓶座} 写出成功: 裴元庆 Person{姓名:雄阔海,性别:娘炮,生肖:龙,星座:射手座} 写出成功: 雄阔海 Person{姓名:你妹,性别:女,生肖:狗,星座:处女座} 写出成功: 你妹 Person{姓名:山本,性别:女,生肖:鸡,星座:天秤座} 写出成功: 山本 Person{姓名:一龙,性别:娘炮,生肖:猴,星座:天蝎座} 写出成功: 一龙