<4> go 工厂

直接上代码


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
阅读更多
文章标签: go
个人分类: go
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

<4> go 工厂

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭