go language to achieve a simple student management system

Remember whether or learn c c ++, Basic will be asked to write a student management system, after learning that the exception does not go also to achieve a simple one.

The main function:

  • 1. Add student information
  • 2. Modify Student Information
  • 3. All student information show

Code section:

First student.go, this part of the main structure is defined and student management and corresponding methods

package main

import "fmt"

//学生
type student struct {
	id    int //唯一的
	name  string
	class string
}

//学生的构造函数
func newstudent(id int, name, class string) *student {
	return &student{
		id:    id,
		name:  name,
		class: class,
	}
}

//学生管理
type manage struct {
	allstudent []*student
}

//学生管理的构造函数
func newmanage() *manage {
	return &manage{allstudent: make([]*student, 0, 100)} //容量是100
}

//1.添加学生
func (s *manage) addstudent(newstu *student) {
	s.allstudent = append(s.allstudent, newstu)
}

//2.编辑学生信息
func (s *manage) modifystudent(newstu *student) {
	for i, v := range s.allstudent {
		if newstu.id == v.id {
			s.allstudent[i] = newstu
			return
		}
	}
	fmt.Printf("系统中不存在学号为%d的这个学生!\n", newstu.id)
}

//3.展示所有学生信息
func (s *manage) showallstudent() {
	for _, v := range s.allstudent {
		fmt.Printf("学号:%d,姓名:%s,班级:%s\n", v.id, v.name, v.class)
	}
}

Then main.go, which is to achieve simple input and menu prompts

package main

import (
	"fmt"
	"os"
)

func menu() {
	fmt.Println("欢迎使用go学生管理系统")
	fmt.Println("1:添加学生")
	fmt.Println("2:编辑学生信息")
	fmt.Println("3:展示所有学生信息")
	fmt.Println("4:退出")
}

func getinput() *student {
	var (
		id    int
		name  string
		class string
	)
	fmt.Println("请输入学生的学号:")
	fmt.Scanf("%d\n", &id)
	fmt.Println("请输入学生的姓名:")
	fmt.Scanf("%s\n", &name)
	fmt.Println("请输入学生的班级")
	fmt.Scanf("%s\n", &class)

	stu := newstudent(id, name, class)
	return stu
}

func main() {
	sm := newmanage()
	for {
		//1.打印菜单
		menu()
		//2.用户选择操作
		var input int
		fmt.Print("请输入你要的操作数:")
		fmt.Scanf("%d\n", &input)
		fmt.Println("你选择的操作是:", input)
		//3.执行操作
		switch input {
		case 1: //添加学生
			stu := getinput()
			sm.addstudent(stu)
		case 2: //编辑学生
			stu := getinput()
			sm.modifystudent(stu)
		case 3: //展示所有学生
			sm.showallstudent()
		case 4: //退出
			os.Exit(0)
		}
	}
}

Operation and results

Run: cd into the folder and then go build
Here Insert Picture Description
Here Insert Picture Description

operation result:
Here Insert Picture Description
Here Insert Picture Description

Published 85 original articles · won praise 55 · views 20000 +

Guess you like

Origin blog.csdn.net/shelgi/article/details/103894195