美文网首页
GO学习笔记(7) - 自建队列代码

GO学习笔记(7) - 自建队列代码

作者: 卡门001 | 来源:发表于2021-07-03 00:01 被阅读0次

扩展已有类型的

程序结构

project
    queue/
        - queue.go
       entry/
           - entry.go
   -go.mod

代码

  • go.mod
module carmen.com/study
go 1.23
  • queue/queue.go
package queue

type Queue []int

func (q *Queue) Push(v int)  {
    *q = append(*q,v)
}

func (q *Queue) Pop() int  {
    head := (*q)[0]
    *q = (*q)[1:]
    return head
}

func (q *Queue) IsEmpty() bool{
    return len(*q) ==0
}

  • queue/entry/entry.go
package main

import (
    "carmen.com/study/queue"
    "fmt"
)

func main() {
    q := queue.Queue{1}
    q.Push(2)
    q.Push(3)
    q.Push(4)
    fmt.Print(q)

    fmt.Println(q.Pop())
    fmt.Println(q.Pop())
    fmt.Println(q.Pop())
    fmt.Println(q.IsEmpty())
    fmt.Println(q.Pop())
    fmt.Println(q.IsEmpty())
}

相关文章

网友评论

      本文标题:GO学习笔记(7) - 自建队列代码

      本文链接:https://www.haomeiwen.com/subject/hhhlultx.html