直接上代码
import (
"errors"
"fmt"
"strings"
)
type Servers []Server
type Server struct {
Name string
}
func ListServer() Servers {
return []Server{
{Name: "app1"},
{Name: "app2"},
{Name: "app3"},
{Name: "app4"},
}
}
func (servers Servers) Filter(name string) (Server, error) {
for _, server := range servers {
if strings.Contains(name, server.Name) {
return server, nil
}
}
return Server{}, errors.New("Not found that server")
}
func main() {
fmt.Println("Start Main func()")
// 创建工厂
servers := ListServer()
// 挑选服务
if server, err := servers.Filter("app1"); err == nil {
fmt.Println("This server is working=>", server.Name)
} else {
fmt.Println("This server is error=>", server.Name)
}
}
// 输入出This server is working=>app1
有疑问加站长微信联系(非本文作者)