Реализация очереди приоритетов в Golang с примером кода

Вот реализация приоритетной очереди в Go (Golang):

package main
import (
    "container/heap"
    "fmt"
)
// Item represents an item in the priority queue.
type Item struct {
    value    string // The value of the item.
    priority int    // The priority of the item.
    index    int    // The index of the item in the heap.
}
// PriorityQueue implements a priority queue data structure.
type PriorityQueue []*Item
// Len returns the length of the priority queue.
func (pq PriorityQueue) Len() int { return len(pq) }
// Less checks if an item at index i has a lower priority than an item at index j.
func (pq PriorityQueue) Less(i, j int) bool {
    return pq[i].priority < pq[j].priority
}
// Swap swaps the positions of items at indexes i and j.
func (pq PriorityQueue) Swap(i, j int) {
    pq[i], pq[j] = pq[j], pq[i]
    pq[i].index = i
    pq[j].index = j
}
// Push adds an item to the priority queue.
func (pq *PriorityQueue) Push(x interface{}) {
    item := x.(*Item)
    item.index = len(*pq)
    *pq = append(*pq, item)
}
// Pop removes the item with the highest priority from the priority queue.
func (pq *PriorityQueue) Pop() interface{} {
    old := *pq
    n := len(old)
    item := old[n-1]
    item.index = -1 // Mark the item as removed
    *pq = old[:n-1]
    return item
}
// Update modifies the priority and value of an item in the priority queue.
func (pq *PriorityQueue) Update(item *Item, value string, priority int) {
    item.value = value
    item.priority = priority
    heap.Fix(pq, item.index)
}
func main() {
    // Creating a new priority queue
    pq := make(PriorityQueue, 0)
    // Adding items to the priority queue
    item1 := &Item{value: "Item 1", priority: 3}
    item2 := &Item{value: "Item 2", priority: 1}
    item3 := &Item{value: "Item 3", priority: 2}
    heap.Push(&pq, item1)
    heap.Push(&pq, item2)
    heap.Push(&pq, item3)
    // Modifying an item's priority and value
    item2.priority = 4
    item2.value = "Updated Item 2"
    heap.Fix(&pq, item2.index)
    // Removing and printing items from the priority queue
    for pq.Len() > 0 {
        item := heap.Pop(&pq).(*Item)
        fmt.Printf("Value: %s, Priority: %d\n", item.value, item.priority)
    }
}

Эта реализация использует пакет container/heapиз стандартной библиотеки Go для построения приоритетной очереди. Он определяет структуру Itemдля хранения значения и приоритета каждого элемента. Тип PriorityQueueпредставляет собой фрагмент указателей Item. Очередь приоритетов поддерживает такие операции, как добавление элементов (Push), удаление элементов с наивысшим приоритетом (Pop) и изменение приоритета и значения элемента (Обновить).