初学GO

发布时间 2023-12-20 21:32:41作者: 文质彬彬赵其辉

完整代码在文章最下方

view

这是一个客户信息管理系统的代码,主要分为三层:view,service和model。其中,view 层负责用户界面的显示和输入,service 层负责业务逻辑的实现,model 层负责数据的存储和操作。

下面我来一步一步讲解这段代码。

首先是导入包:


import (
	"fmt"
	"study/model"
	"study/service"
)

这里导入了 fmt、model 和 service 三个包。

接下来是定义 CustomerView 结构体:


type CustomerView struct {
	key             string //接收用户输入...
	loop            bool   //表示是否循环的显示主菜单
	customerService *service.CustomerService
}

CustomerView 结构体包含三个属性:key 表示用户输入的选项,loop 表示程序是否继续运行,customerService 是指向 service 层的指针,用来调用其中的方法。

然后是 mainMenu 方法:

func (this *CustomerView) mainMenu() {
	for {
		fmt.Println("-----------------客户信息管理软件-----------------")
		fmt.Println(" 1 添 加 客 户")
		fmt.Println(" 2 修 改 客 户")
		fmt.Println(" 3 删 除 客 户")
		fmt.Println(" 4 客 户 列 表")
		fmt.Println(" 5 退 出")
		fmt.Print("请选择(1-5):")

		fmt.Scanln(&this.key)
		switch this.key {
		case "1":
			this.add()
		case "2":
			this.modify()
		case "3":
			this.delete()
		case "4":
			this.list()
		case "5":
			this.loop = false
		default:
			fmt.Println("你的输入有误,请重新输入...")
		}
		if !this.loop {
			break
		}
	}
	fmt.Println("你退出了客户关系管理系统...")

}

mainMenu 方法是客户信息管理系统的主要功能,其中先使用 fmt 包输出了菜单选项,然后根据用户输入的选项调用相应的方法。如果用户选择了 5,loop 将被设置为 false,程序将结束。

list、add、modify 和 delete 方法分别用于显示客户列表、添加客户、修改客户和删除客户。

最后是 main 函数:

func main() {
	customerView := CustomerView{
		key:             "",
		loop:            true,
		customerService: service.NewCustomerService(), // 初始化 customerService
	}

	customerView.mainMenu()
	customerView.add()
	customerView.modify()
	customerView.delete()

}
在 main 函数中,定义了一个 CustomerView 结构体,初始化了 key、loop 和 customerService,然后调用了 mainMenu、add、modify 和 delete 方法。

关键字和函数解释:

fmt:Go 语言标准库中提供的格式化输出和输入的函数库。
struct:用于定义自定义数据类型的关键字,类似于 Java 中的类。
method:在 Go 语言中,方法是指与某种特定类型关联的函数,它们可以访问该类型的数据。定义方法的语法为 func (接收者) 方法名(参数列表) 返回值列表 {},其中接收者可以是值类型或指针类型。
switch:用于执行多个条件分支的语句,类似于 C 语言中的 switch 语句。
Scanln:从标准输入中读取一行数据,并将其存储到指定变量中。
NewCustomerService:创建一个新的 CustomerService 对象。

model

package model

import (
	"fmt"
)

在 model 包中引入了 fmt 包,用于格式化输出。

// 声明一个Customer结构体,表示一个客户信息
type Customer struct {
	Id     int
	Name   string
	Gender string
	Age    int
	Phone  string
	Email  string
}

定义了一个名为 Customer 的结构体,用于表示客户信息。它包含了客户的属性:Id (整型)、Name (字符串)、Gender (字符串)、Age (整型)、Phone (字符串) 和 Email (字符串)。

// 使用工厂模式,返回一个Customer的实例
func NewCustomer(id int, name string, gender string,
	age int, phone string, email string) Customer {
	return Customer{
		Id:     id,
		Name:   name,
		Gender: gender,
		Age:    age,
		Phone:  phone,
		Email:  email,
	}
}

NewCustomer 是一个函数,采用工厂模式创建并返回一个 Customer 实例。它接受 id (整型)、name (字符串)、gender (字符串)、age (整型)、phone (字符串) 和 email (字符串) 作为参数,使用这些参数初始化并返回一个新的 Customer 实例。

// 第二种创建Customer实例方法,不带id
func NewCustomer2(name string, gender string,
	age int, phone string, email string) Customer {
	return Customer{
		Name:   name,
		Gender: gender,
		Age:    age,
		Phone:  phone,
		Email:  email,
	}
}

NewCustomer2 是另一种创建 Customer 实例的方法,不带 id 参数。它接受 name (字符串)、gender (字符串)、age (整型)、phone (字符串) 和 email (字符串) 作为参数,使用这些参数初始化并返回一个新的 Customer 实例。

// 返回用户的信息,格式化的字符串
func (this Customer) GetInfo() string {
	info := fmt.Sprintf("%v\t%v\t%v\t%v\t%v\t%v\t", this.Id,
		this.Name, this.Gender, this.Age, this.Phone, this.Email)
	return info
}

GetInfo 是一个方法,它属于 Customer 结构体。它返回一个包含客户信息的格式化字符串。使用 fmt.Sprintf 函数将 this 的属性值格式化为字符串,并通过 return 语句返回该字符串。

以上就是该份代码的详细解释,它定义了一个用于表示客户信息的结构体 Customer,提供了两种方式来创建实例,并提供了获取客户信息的方法。

CustomerService


package service

import (
	"study/model"
)

在 service 包中引入了 study/model 包,用于使用 model 包中定义的 Customer 结构体。


// 该CustomerService, 完成对Customer的操作,包括
// 增删改查
type CustomerService struct {
	customers   []model.Customer
	customerNum int
}

CustomerService 是一个结构体,用于完成对客户的增删改查操作。它包含了 customers (切片类型,存储客户信息) 和 customerNum (整型,表示当前切片中客户的数量) 两个字段。

// 编写一个方法,可以返回 *CustomerService
func NewCustomerService() *CustomerService {
	customerService := &CustomerService{}
	customerService.customerNum = 1
	customer := model.NewCustomer(1, "张三", "男", 20, "112", "zs@sohu.com")
	customerService.customers = append(customerService.customers, customer)
	return customerService
}
NewCustomerService 是一个函数,用于创建并返回一个 CustomerService 的实例。它初始化了一个 CustomerService 对象,并添加了一个初始客户到 customers 切片中。
// 返回客户切片
func (this *CustomerService) List() []model.Customer {
	return this.customers
}
List 是一个方法,属于 CustomerService 结构体。它返回存储在 customers 字段中的客户切片。

go
func (this *CustomerService) Add(customer model.Customer) bool {
	this.customerNum++
	customer.Id = this.customerNum
	this.customers = append(this.customers, customer)
	return true
}
Add 是一个方法,属于 CustomerService 结构体。它接受一个 customer 参数(类型为 model.Customer),将其添加到 customers 切片中,并生成一个唯一的客户ID。
func (this *CustomerService) Update(id int, customer model.Customer) bool {
	for index, c := range this.customers {
		if c.Id == id {
			// 更新客户信息
			this.customers[index] = customer
			return true
		}
	}
	return false
}

Update 是一个方法,属于 CustomerService 结构体。它接受一个 id 参数(整型)和一个 customer 参数(类型为 model.Customer),通过遍历 customers 切片找到对应的客户,并更新其信息。

func (this *CustomerService) Delete(id int) bool {
	for index, customer := range this.customers {
		if customer.Id == id {
			// 从切片中删除客户
			this.customers = append(this.customers[:index], this.customers[index+1:]...)
			return true
		}
	}
	return false
}

Delete 是一个方法,属于 CustomerService 结构体。它接受一个 id 参数(整型),通过遍历 customers 切片找到对应的客户,并从切片中删除该客户。

以上就是该份代码的详细解释,它定义了一个用于管理客户信息的服务 CustomerService,提供了新增、删除、更新和查询客户信息的方法。

view.go

package main

import (
	"fmt"
	"study/model"
	"study/service"
)

// CustomerView【view 层】
// 1、显示界面
// 2、接收用户输入
// 3、根据用户输入,调用 customerService 的方法完成客户的管理【修改,删除,显示等】
type CustomerView struct {
	key             string //接收用户输入...
	loop            bool   //表示是否循环的显示主菜单
	customerService *service.CustomerService
}

func (this *CustomerView) mainMenu() {
	for {
		fmt.Println("-----------------客户信息管理软件-----------------")
		fmt.Println(" 1 添 加 客 户")
		fmt.Println(" 2 修 改 客 户")
		fmt.Println(" 3 删 除 客 户")
		fmt.Println(" 4 客 户 列 表")
		fmt.Println(" 5 退 出")
		fmt.Print("请选择(1-5):")

		fmt.Scanln(&this.key)
		switch this.key {
		case "1":
			this.add()
		case "2":
			this.modify()
		case "3":
			this.delete()
		case "4":
			this.list()
		case "5":
			this.loop = false
		default:
			fmt.Println("你的输入有误,请重新输入...")
		}
		if !this.loop {
			break
		}
	}
	fmt.Println("你退出了客户关系管理系统...")
}

// 显示所有的客户信息
func (this *CustomerView) list() {

	//首先,获取到当前所有的客户信息(在切片中)
	customers := this.customerService.List()
	//显示
	fmt.Println("---------------------------客户列表---------------------------")
	fmt.Println("编号\t姓名\t性别\t年龄\t电话\t邮箱")
	for i := 0; i < len(customers); i++ {
		//fmt.Println(customers[i].Id,"\t", customers[i].Name...)
		fmt.Println(customers[i].GetInfo())
	}
	fmt.Printf("\n-------------------------客户列表完成-------------------------\n\n")
}
func (this *CustomerView) add() {
	fmt.Println("---------------------添加客户---------------------")
	fmt.Println("姓名:")
	name := ""
	fmt.Scanln(&name)
	fmt.Println("性别:")
	gender := ""
	fmt.Scanln(&gender)
	fmt.Println("年龄:")
	age := 0
	fmt.Scanln(&age)
	fmt.Println("电话:")
	phone := ""
	fmt.Scanln(&phone)
	fmt.Println("电邮:")
	email := ""
	fmt.Scanln(&email)
	customer := model.NewCustomer2(name, gender, age, phone, email)
	if this.customerService.Add(customer) {
		fmt.Println("~~~~~~~~~~~~~~添加完成~~~~~~~~~")
	} else {
		fmt.Println("!!!!!!!!!失败")
	}
}
func (this *CustomerView) modify() {
	fmt.Println("---------------------修改客户---------------------")
	fmt.Print("请选择需要修改的客户编号(-1退出):")
	id := -1
	fmt.Scanln(&id)
	if id == -1 {
		return
	}
	for _, customer := range this.customerService.List() {
		if customer.Id == id {
			fmt.Printf("姓名(%v):", customer.Name)
			name := ""
			fmt.Scanln(&name)
			fmt.Printf("性别(%v):", customer.Gender)
			gender := ""
			fmt.Scanln(&gender)
			fmt.Printf("年龄(%v):", customer.Age)
			age := 0
			fmt.Scanln(&age)
			fmt.Printf("电话(%v):", customer.Phone)
			phone := ""
			fmt.Scanln(&phone)
			fmt.Printf("电邮(%v):", customer.Email)
			email := ""
			fmt.Scanln(&email)
			newCustomer := model.NewCustomer(id, name, phone, age, email, gender)
			if this.customerService.Update(id, newCustomer) {
				fmt.Println("完成!!!!!!!!!!")
			} else {
				fmt.Println("失败!!!!!!!")
			}
			return
		}

	}
	fmt.Println("该客户不存在")
}
func (this *CustomerView) delete() {
	fmt.Println("---------------------删除客户---------------------")
	fmt.Print("请选择需要删除的客户编号(-1退出):")
	id := -1
	fmt.Scanln(&id)
	if id == -1 {
		return
	}
	if this.customerService.Delete(id) {
		fmt.Println("删除成功")
	} else {
		fmt.Println("该客户不存在")
	}
}
func main() {
	customerView := CustomerView{
		key:             "",
		loop:            true,
		customerService: service.NewCustomerService(), // 初始化 customerService

	}

	customerView.mainMenu()
	customerView.add()
	customerView.modify()
	customerView.delete()
}

model.go

package model

import (
	"fmt"
)

// 声明一个Customer结构体,表示一个客户信息
type Customer struct {
	Id     int
	Name   string
	Gender string
	Age    int
	Phone  string
	Email  string
}

// 使用工厂模式,返回一个Customer的实例
func NewCustomer(id int, name string, gender string,
	age int, phone string, email string) Customer {
	return Customer{
		Id:     id,
		Name:   name,
		Gender: gender,
		Age:    age,
		Phone:  phone,
		Email:  email,
	}
}

// 第二种创建Customer实例方法,不带id
func NewCustomer2(name string, gender string,
	age int, phone string, email string) Customer {
	return Customer{
		Name:   name,
		Gender: gender,
		Age:    age,
		Phone:  phone,
		Email:  email,
	}
}

// 返回用户的信息,格式化的字符串
func (this Customer) GetInfo() string {
	info := fmt.Sprintf("%v\t%v\t%v\t%v\t%v\t%v\t", this.Id,
		this.Name, this.Gender, this.Age, this.Phone, this.Email)
	return info
}

customerService.go

package service

import (
	"study/model"
)

// 该CustomerService, 完成对Customer的操作,包括
// 增删改查
type CustomerService struct {
	customers []model.Customer
	//声明一个字段,表示当前切片含有多少个客户
	//该字段后面,还可以作为新客户的id+1
	customerNum int
}

// 编写一个方法,可以返回 *CustomerService
func NewCustomerService() *CustomerService {
	//为了能够看到有客户在切片中,我们初始化一个客户
	customerService := &CustomerService{}
	customerService.customerNum = 1
	customer := model.NewCustomer(1, "张三", "男", 20, "112", "zs@sohu.com")
	customerService.customers = append(customerService.customers, customer)
	return customerService
}

// 返回客户切片
func (this *CustomerService) List() []model.Customer {
	return this.customers
}
func (this *CustomerService) Add(customer model.Customer) bool {
	this.customerNum++
	customer.Id = this.customerNum
	this.customers = append(this.customers, customer)
	return true
}
func (this *CustomerService) Update(id int, customer model.Customer) bool {
	for index, c := range this.customers {
		if c.Id == id {
			// 更新客户信息
			this.customers[index] = customer
			return true
		}
	}
	return false
}
func (this *CustomerService) Delete(id int) bool {
	for index, customer := range this.customers {
		if customer.Id == id {
			// 从切片中删除客户
			this.customers = append(this.customers[:index], this.customers[index+1:]...)
			return true
		}
	}
	return false
}