571
社区成员
发帖
与我相关
我的任务
分享用Go语言实现LinkTable库,更新menu项目
func main() {
list := &LinkTable{
head: nil,
tail: nil,
SumofNode: 0,
}
cmd1 := createCmd("order", "show order Cmd", new(cmd_order))
cmd2 := createCmd("version", "show version Cmd", new(cmd_version))
cmd3 := createCmd("help", "show help Cmd", new(cmd_help))
cmd4 := createCmd("quit", "show quit Cmd", new(cmd_quit))
list.insertNode(cmd1)
list.insertNode(cmd2)
list.insertNode(cmd3)
list.insertNode(cmd4)
list.delectNode(cmd2)
for {
showAllCmd()
var command string
fmt.Scan(&command)
list.execCmd(command)
if command == "quit" {
break
}
}
}
func showAllCmd() {
fmt.Print("---------------Menu v 2.0---------------\n>")
fmt.Print(" Enter your choice \n>")
fmt.Print(" 1. order 2. version \n>")
fmt.Print(" 3. help 4. quit \n>")
}
首先定义链表的数据结构以及command的数据结构
type LinkTable struct {
head *CmdNode //头节点
tail *CmdNode //尾节点
SumofNode int //节点总数
}
type CmdNode struct {
cmd string //指令名称
desc string //指令描述
cmd_handler handler //执行方法
next *CmdNode //下个节点
}
type handler interface {
exec()
}
func createCmd(name string, desc string, handler handler) *CmdNode {
return &CmdNode{
cmd: name,
desc: desc,
cmd_handler: handler,
}
}
func (this *LinkTable) execCmd(name string) error {
node := this.findNode(name)
if node == nil {
println("no such cmd!")
return nil
}
node.cmd_handler.exec()
return nil
}
func (this *LinkTable) insertNode(node *CmdNode) error {
//判断是否存在
if this.findNode(node.cmd) != nil {
return errors.New("The command already exists!")
}
//判断是否存在头节点
if this.head == nil {
this.head = node
this.tail = node
this.SumofNode = 1
return nil
}
//存在头节点
this.SumofNode++
this.tail.next = node
this.tail = this.tail.next
return nil
}
func (this *LinkTable) delectNode(node *CmdNode) error {
//判断是否存在
if this.findNode(node.cmd) == nil {
return errors.New("The command does not exist!")
}
var temp_head *CmdNode = this.head
var temp_tail *CmdNode = this.tail
temp_head.next = temp_tail
return nil
}
func (this *LinkTable) findNode(cmd string) *CmdNode {
for n := this.head; n != nil; n = n.next {
if n.cmd == cmd {
return n
}
}
return nil
}
type cmd_order struct {
}
func (this cmd_order) exec() {
println("This is order command!")
}
type cmd_help struct {
}
func (this cmd_help) exec() {
println("This is help command!")
}
type cmd_version struct {
}
func (this cmd_version) exec() {
println("Menu verison = 2.0!")
}
type cmd_quit struct {
}
func (this cmd_quit) exec() {
println("You have successfully exited")
}


