Hi,
I’m new to Go and trying to use it in a assignment about knowledge graphs.
The way I’m implementing this is as follows:
- I have a class Node that have a name and named relationships. It should not be used directly.
- I want a class Concept and a class Instance that both “inherit” Node.
…and that’s where I have trouble
Because a Concept isn’t a Node (in Go), my method AddRelationship on Node can’t work on a Concept.
My first idea was to use an interface, but I’m a bit lost and what I tried doesn’t seems to work.
So, my “class” Node that works:
package main
import "fmt"
// a node in the sense of a knowledge graph. Shouldn't be used directly.
type Node struct {
name string
relationships map[string][]*Node
}
// Constructor of node
func NewNode(name string) *Node {
return &Node{
name: name,
// relationships have a name
relationships: make(map[string][]*Node),
}
}
func (n *Node) GetName() string {
return n.name
}
// Add a relationship to the node
func (n *Node) AddRelationship(name string, node *Node) {
n.relationships[name] = append(n.relationships[name], node)
}
// Find relationships by name
func (n *Node) Find(name string) []*Node {
return n.relationships[name]
}
// Print the node and its relationships
func (n *Node) Print() {
fmt.Println("[", n.name, "]")
for relationName, nodes := range n.relationships {
for _, node := range nodes {
fmt.Println(" \u2514\u2500(", relationName, ")->[", node.GetName(), "]")
}
}
}
Simple example:
package main
func main() {
node := NewNode("Paul")
node.AddRelationship("is-a", NewNode("Humain"))
node.Print()
}
$ go run ./main.go ./node.go
[ Paul ]
└─( is-a )->[ Humain ]
What I tried with my Concept class:
Defining an interface
type INode interface {
AddRelationship(name string, node *INode)
Find(name string) []INode
GetName() string
Print()
}
and replacing every parameter and output in the previous code with INode
(instead of *Node
).
But even if I implemented all the method, Concept isn’t recognized as INode
.
package main
// A concept is a node in the sense of a knowledge graph.
type Concept struct {
Node
}
func NewConcept(name string) *Concept {
return &Concept{
Node: *NewNode(name),
}
}
func (c *Concept) GetName() string {
return c.Node.GetName()
}
// I read that in parameters, *INode and INode behave the same as it's a interface?
func (c *Concept) AddRelationship(name string, node INode) {
c.Node.AddRelationship(name, node)
}
func (c *Concept) Find(name string) []INode {
return c.Node.Find(name)
}
func (c *Concept) Print() {
c.Node.Print()
}
So what am I missing in Go’s inheritence system?