用go语言实现一个构建有向图的函数,同时图结构的点和边上都支持添加属性

当然可以。下面是一个简单的用Go语言实现的有向图构建函数的示例。这个图结构使用map来存储,每个节点都由一个唯一的标识符(id)表示,并且节点和边都可以附加属性。

go

package main  
  
import (  
 "fmt"  
)  
  
// 定义节点结构体  
type Node struct {  
 ID       string  
 Attributes map[string]interface{}  
}  
  
// 定义边结构体  
type Edge struct {  
 Source, Target string  
 Attributes      map[string]interface{}  
}  
  
// 定义有向图结构体  
type DirectedGraph struct {  
 Nodes  map[string]*Node  
 Edges  map[string]*Edge  
}  
  
// 创建一个新的有向图  
func NewDirectedGraph() *DirectedGraph {  
 return &DirectedGraph{  
 Nodes: make(map[string]*Node),  
 Edges: make(map[string]*Edge),  
 }  
}  
  
// 添加节点到图中  
func (g *DirectedGraph) AddNode(id string, attributes map[string]interface{}) {  
 if _, ok := g.Nodes[id]; !ok {  
 g.Nodes[id] = &Node{ID: id, Attributes: attributes}  
 } else {  
 fmt.Printf("节点 %s 已存在.\n", id)  
 }  
}  
  
// 添加边到图中  
func (g *DirectedGraph) AddEdge(source, target string, attributes map[string]interface{}) {  
 if _, ok := g.Edges[source]; !ok {  
 g.Edges[source] = &Edge{Source: source, Target: target, Attributes: attributes}  
 } else {  
 fmt.Printf("边 %s-%s 已存在.\n", source, target)  
 }  
}  
  
// 打印图中的节点和边及其属性  
func (g *DirectedGraph) PrintGraph() {  
 for id, node := range g.Nodes {  
 fmt.Printf("节点 %s: %+v\n", id, node.Attributes)  
 }  
 for source, edge := range g.Edges {  
 fmt.Printf("边 %s-%s: %+v\n", source, edge.Target, edge.Attributes)  
 }  
}  
  
func main() {  
 graph := NewDirectedGraph()  
 graph.AddNode("A", map[string]interface{}{"color": "red"}) // 添加节点 A,属性为 color: red  
 graph.AddNode("B", map[string]interface{}{"color": "blue"}) // 添加节点 B,属性为 color: blue  
 graph.AddEdge("A", "B", map[string]interface{}{"weight": 2}) // 添加从 A 到 B 的边,属性为 weight: 2  
 graph.PrintGraph() // 打印图中的节点和边及其属性  
}

这个示例代码创建了一个有向图,并添加了两个节点(A和B)和一个从A到B的边。每个节点和边都有附加的属性(例如颜色和重量)。最后,通过调用PrintGraph函数,可以打印出图中的所有节点和边及其属性。

你可能感兴趣的:(golang,数据库,服务器)