定义数据
首先,我们需要定义两个结构体:House(房屋)和Tenant(租客)。House结构体包含房屋的基本信息,如编号、地址、租金等;Tenant结构体包含租客的个人信息,如姓名、电话等。
type House struct {
ID int
Address string
Rent float64
}
type Tenant struct {
Name string
Phone string
}
初始化示例数据:
为了方便测试,我们可以在程序启动时初始化一些示例数据,比如添加一些房屋和租客的信息。
func initializeData() []House {
houses := []House{
{ID: 1, Address: "青训营1", Rent: 1000},
{ID: 2, Address: "青训营2", Rent: 1200},
// 添加更多房屋信息...
}
return houses
}
实现功能: 接下来,我们实现以下基本功能:
- 查询所有房屋信息
- 查询特定房屋信息
- 添加房屋信息
- 删除房屋信息
- 租赁房屋
func getAllHouses(houses []House) {
for _, house := range houses {
fmt.Printf("House ID: %d, Address: %s, Rent: %.2f\n", house.ID, house.Address, house.Rent)
}
}
func getHouseByID(houses []House, id int) {
for _, house := range houses {
if house.ID == id {
fmt.Printf("House ID: %d, Address: %s, Rent: %.2f\n", house.ID, house.Address, house.Rent)
return
}
}
fmt.Println("没有找到房屋.")
}
func addHouse(houses *[]House, newHouse House) {
*houses = append(*houses, newHouse)
fmt.Println("房屋添加成功.")
}
func deleteHouse(houses *[]House, id int) {
for i, house := range *houses {
if house.ID == id {
*houses = append((*houses)[:i], (*houses)[i+1:]...)
fmt.Println("房屋退房成功.")
return
}
}
fmt.Println("没有找到房屋.")
}
func rentHouse(houses *[]House, id int, tenant Tenant) {
for i, house := range *houses {
if house.ID == id {
(*houses)[i].Rent -= 100 // 假设租金每月减100
fmt.Printf("House rented to %s, remaining rent: %.2f\n", tenant.Name, house.Rent)
return
}
}
fmt.Println("没有找到房屋.")
}
用户界面:
为了与用户交互,我们可以实现一个简单的命令行界面,接收用户输入并调用对应的功能函数。
func main() {
houses := initializeData()
for {
fmt.Println("1. 查询所有房屋")
fmt.Println("2. 查询房屋by ID")
fmt.Println("3. 添加一间新房屋")
fmt.Println("4. 删除房屋by ID")
fmt.Println("5. 出租一间房屋")
fmt.Println("6. 退出")
var choice int
fmt.Print("请选择 ")
fmt.Scanln(&choice)
switch choice {
case 1:
getAllHouses(houses)
case 2:
var id int
fmt.Print("Enter the house ID: ")
fmt.Scanln(&id)
getHouseByID(houses, id)
case 3:
var newHouse House
fmt.Print("Enter house ID: ")
fmt.Scanln(&newHouse.ID)
fmt.Print("Enter house address: ")
fmt.Scanln(&newHouse.Address)
fmt.Print("Enter house rent: ")
fmt.Scanln(&newHouse.Rent)
addHouse(&houses, newHouse)
case 4:
var id int
fmt.Print("Enter the house ID to delete: ")
fmt.Scanln(&id)
deleteHouse(&houses, id)
case 5:
var id int
fmt.Print("Enter the house ID to rent: ")
fmt.Scanln(&id)
var tenant Tenant
fmt.Print("Enter tenant name: ")
fmt.Scanln(&tenant.Name)
fmt.Print("Enter tenant phone: ")
fmt.Scanln(&tenant.Phone)
rentHouse(&houses, id, tenant)
case 6:
fmt.Println("退出中...")
return
default:
fmt.Println("不存在的选项,请重新尝试.")
}
fmt.Println()
}
}
总结:
通过以上步骤,我们已经完成了一个简单的房屋出租管理系统。这个系统可以让用户进行房屋信息的查询、添加、删除以及租赁操作。这个项目帮助我巩固了GO语言的基本知识和实践经验,并且实现了有条理性的代码结构,使得代码易于维护和扩展。希望这个示例能对其他GO语言初学者有所帮助,让大家在学习过程中能够更好地掌握GO语言的应用。