golang中结构体指针的应用

package main

import (
	"fmt"
)

type School struct {
	brand string
	city  string
}
type Class struct {
	name string
	number int
	*School
}

func main() {
	// 创建学校
	s1 := &School{brand: "一中", city: "北京"}

	var classSlice []Class
	var cls Class
	// 循环创建班级
	for {
		fmt.Printf("请输入班级名:")
		fmt.Scan(&cls.name)
		if cls.name == "Q" || cls.name == "q" {
			break
		}
		fmt.Printf("请输入班级人数:")
		fmt.Scan(&cls.number)
		// 添加班级所属学校
		cls.School = s1
		// 将班级添加到班级切片中去
		classSlice = append(classSlice, cls)
	}
	fmt.Println(classSlice)

	for _, cls := range classSlice {
		message := fmt.Sprintf("%s-%d-%s-%s", cls.name, cls.number, cls.School.city, cls.School.brand)
		fmt.Println(message)
	}
}

  

posted @ 2021-10-10 17:58  专职  阅读(53)  评论(0编辑  收藏  举报