Last active
April 28, 2024 15:46
-
-
Save rof20004/3038cb3e68cb7fdf91c357f7e1ce3910 to your computer and use it in GitHub Desktop.
Go queue implementation with generics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type User struct { | |
Id int | |
Name string | |
} | |
// Define a struct for the Queue | |
type Queue[V any] struct { | |
items []V | |
} | |
// Enqueue adds an element to the end of the queue | |
func (q *Queue[V]) Enqueue(item V) { | |
q.items = append(q.items, item) | |
} | |
// Dequeue removes the first element from the queue | |
func (q *Queue[V]) Dequeue() { | |
if len(q.items) == 0 { | |
return | |
} | |
q.items = q.items[1:] | |
} | |
// GetAll returns all values currently in the queue | |
func (q *Queue[V]) GetAll() []V { | |
return q.items | |
} | |
func main() { | |
// Create a new queue | |
queue := Queue[User]{} | |
// Enqueue some elements | |
queue.Enqueue(User{Id: 1, Name: "Jaspion"}) | |
queue.Enqueue(User{Id: 2, Name: "Jiraya"}) | |
queue.Enqueue(User{Id: 3, Name: "Jiban"}) | |
fmt.Println("Queue before dequeue:", queue) | |
// Dequeue an element | |
queue.Dequeue() | |
fmt.Println("Queue after dequeue:", queue) | |
// Get all elements | |
allItems := queue.GetAll() | |
fmt.Println("All items:", allItems) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment