💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] ## 示例 ### 计算形状 <details> <summary>main.go</summary> ``` package main import "fmt" type shape interface { getType() string accept(visitor) } // 方形 type square struct { side int } func (s *square) accept(v visitor) { v.visitForSquare(s) } func (s *square) getType() string { return "Square" } // 圆形 type circle struct { radius int } func (c *circle) accept(v visitor) { v.visitForCircle(c) } func (c *circle) getType() string { return "Circle" } // 矩形 type rectangle struct { l int b int } func (t *rectangle) accept(v visitor) { v.visitForrectangle(t) } func (t *rectangle) getType() string { return "rectangle" } type visitor interface { visitForSquare(*square) visitForCircle(*circle) visitForrectangle(*rectangle) } // 面积计算器 type areaCalculator struct { area int } func (a *areaCalculator) visitForSquare(s *square) { // Calculate area for square. // Then assign in to the area instance variable. fmt.Println("Calculating area for square") } func (a *areaCalculator) visitForCircle(s *circle) { fmt.Println("Calculating area for circle") } func (a *areaCalculator) visitForrectangle(s *rectangle) { fmt.Println("Calculating area for rectangle") } // 中间坐标 type middleCoordinates struct { x int y int } func (a *middleCoordinates) visitForSquare(s *square) { // Calculate middle point coordinates for square. // Then assign in to the x and y instance variable. fmt.Println("Calculating middle point coordinates for square") } func (a *middleCoordinates) visitForCircle(c *circle) { fmt.Println("Calculating middle point coordinates for circle") } func (a *middleCoordinates) visitForrectangle(t *rectangle) { fmt.Println("Calculating middle point coordinates for rectangle") } func main() { square := &square{side: 2} circle := &circle{radius: 3} rectangle := &rectangle{l: 2, b: 3} areaCalculator := &areaCalculator{} square.accept(areaCalculator) circle.accept(areaCalculator) rectangle.accept(areaCalculator) fmt.Println() middleCoordinates := &middleCoordinates{} square.accept(middleCoordinates) circle.accept(middleCoordinates) rectangle.accept(middleCoordinates) } ``` </details> <br /> 输出 ``` Calculating area for square Calculating area for circle Calculating area for rectangle Calculating middle point coordinates for square Calculating middle point coordinates for circle Calculating middle point coordinates for rectangle ```