golang构造函数
2024-09-04 14:25:44
http://blog.jobbole.com/107442/?utm_source=blog.jobbole.com&utm_medium=relatedPosts
https://gocn.vip/question/1420
构造函数
type Person {
name string,
age int64,
country string,
...
}
func NewPerson(name string,age int64,country sting)*Person{
return &Person{ name: name,
}
package main
import (
"fmt"
)
type options struct {
a int64
b string
c map[int]string
}
func NewOption(opt ...ServerOption) *options {
r := new(options)
for _, o := range opt {
o(r)
}
return r
}
type ServerOption func(*options)
func WriteA(s int64) ServerOption {
return func(o *options) {
o.a = s
}
}
func WriteB(s string) ServerOption {
return func(o *options) {
o.b = s
}
}
func WriteC(s map[int]string) ServerOption {
return func(o *options) {
o.c = s
}
}
func main() {
opt1 := WriteA(int64(1))
opt2 := WriteB("test")
opt3 := WriteC(make(map[int]string,0))
op := NewOption(opt1, opt2, opt3)
fmt.Println(op.a, op.b, op.c)
}
func NewServer(addr string, options ...func(*Server)) (*Server, error) {
srv := &Server{
Addr: addr,
}
for _, option := range options {
option(srv)
}
return srv
}
func timeout(d time.Duration) func(*Server) {
return func(srv *Server) {
srv.timeout = d
}
}
func tls(c *config) func(*Server) {
return func(srv *Server) {
Tls := loadConfig(c)
srv.tls = Tls
}
}
//使用
src, err = NewServer("localhost:8080", timeout(1), tls(path/to/cert))
类工厂模式
// 存放 <cond, handler> 对应关系
var mux map[string]func(option *Option) error
// 注册handler
func register(key string, f func(option *Option) error) {
if mux == nil {
mux = make(map[string]func(option *Option) error)
}
if _, exist := mux[key]; exist {
return errors.New("handler exist")
}
mux[key] = f
}
// factory
func factory(option *Option) error {
return mux[option.Key](option)
}
最新文章
- [LeetCode] Letter Combinations of a Phone Number 电话号码的字母组合
- iOS程序破解——获取.ipa程序包
- CF 268E Playlist(贪心)
- django 安装
- FAQ_1_陌生的VERSION.SDK_INT
- 关于 jquery select2 多个关键字 模糊查询的解决方法
- [转]Linq中GroupBy方法的使用总结
- DMALL刘江峰:生鲜市场具有巨大O2O改造空间
- id,class,name区别
- Oracle 常用命令
- Ehcache详细解读(转载)
- Mac OS X 10.10(yosemite)更新后,cocoapods出错, 及cocoapods更新至0.34后, 错误情况整理
- Python核心编程笔记--unicode编码
- 树莓派高级GPIO库,wiringpi2 for python使用笔记(五)i2c读取测试
- Android - 采用ApiDemos得知Android开展
- VMware vCloud与Zend Server实现PHP应用程序自动化交付
- mybatis返回list
- POLARDB &#183; 最佳实践 &#183; POLARDB不得不知道的秘密(二)
- 上传jar包到maven中央仓库过程中遇到的一些问题总结!
- paste