'type assertion of custom type in go using interface{}
Hi Im new to go and I'm trying implement data structures and algos in go as a learning process. I am trying to interfaces as generics values but I cannot seem to get my custom type of vertex to function properly. I have attached a link to a go playground
type Vertex struct{
Adjacent DoubleLinkedList.DLinkedList
Weight int
Origin int
}
type UGraph struct{
Vertices map[int]DoubleLinkedList.DLinkedList
Weight int
counter int
VerticesList []*Vertex
}
func (UG *UGraph) BFS(node *Vertex, Value interface{})(int) {
visited := make(map[*Vertex]bool) // map that acts as a set
var queue Queue.Queue
queue.Enqueue(node)
for queue.Store.Size > 0 {
V, _ := queue.Dequeue()
nodes := UG.Vertices[((V).(Vertex).Origin).(int64)]
head := nodes.Head
for head.Next != nil {
head = head.Next
if head.Value == Value{
return head.Value.Origin
}
if visited[(head.Value.Origin).(int64)] != true{
visited[head.Value.Origin] = true
queue.Enqueue(head)
}
}
}
return 0
}
Solution 1:[1]
If I understand correctly your issue, this seems to be your starting point:
You need a Queue with generics support. Then you need to update all structures to handle a T generic type like in the example below.
Be aware that once you have a type T in your struct, your method signature must be updated
You don’t need to use Generics on each type. You may want to use a field with an existing type like Queue[int]
Here we will consider you want all be generic
Enjoy
type DListNode[T any] struct {
Prev *DListNode[T]
Next *DListNode[T]
Value T
}
func (DLL *DLinkedList[T]) AddFront(value T) {
…
}
type Queue[T any] struct {
Store DLinkedList[T] // consider store a pointer
Capacity int
Front T
Rear T
}
func (QQ *Queue[T]) Enqueue(value T) error {
…
}
func (QQ *Queue[T]) Dequeue() (T, error) {
if QQ.isEmpty() {
var zero T
return zero, fmt.Errorf("Queue is currently Empty")
}
…
}
…
// omitting some steps, you can see that you need this in the end:
func (UG *UGraph[T]) BFS(node *Vertex[T], value T) T {
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tiago Peczenyj |
