Golang面向对象编程之构造函数【struct&new】


本文摘自网络,作者,侵删。

Golang面向对象编程之构造函数【struct&new】

201808

构造函数是一种特殊的方法,主要用来在创建对象时初始化对象,即为对象成员变量赋初始值。特别的一个类可以有多个构造函数 ,可根据其参数个数的不同或参数类型的不同来区分它们,即构造函数的重载。

Golang里面没有构造函数,但是Golang却可以像C++一样实现类似继承、构造函数一样等面向对象编程的思想和方法。Golang里面要实现相关的构造函数定义可以通过通过new来创建构造函数。

一个简单的构造函数的实现


定义一个结构

type ContentMsg struct {
    EffectId int         `json:"effect_id"`
    Text     string      `json:"text"`
    Data     interface{} `json: "data"`
}
复制代码

通过new一个对象,或者利用Golang本身的&方式来生成一个对象并返回一个对象指针:

unc NewContentMsg(data, effectId int) *ContentMsg {
    instance := new(ContentMsg)
    instance.Data = data
    instance.EffectId = effectId
    return instance
}

func NewContentMsgV2(data, effectId int) *ContentMsg {
    return &ContentMsg{
        Data:     data,
        EffectId: effectId,
    }
}

复制代码

更为优雅的构造的函数的实现


/*
一个更为优雅的构造函数的实现方式

参考:
* 1,项目:"gitlab.xxx.com/xxx/redis"
* 2,链接:https://commandcenter.blogspot.com/2014/01/self-referential-functions-and-design.html

通过这个方式可以方便构造不同对象,同时避免了大量重复代码

*/

package main

import (
    "fmt"
    "time"

    "golang.org/x/net/context"
)

type Cluster struct {
    opts options
}

type options struct {
    connectionTimeout time.Duration
    readTimeout       time.Duration
    writeTimeout      time.Duration
    logError          func(ctx context.Context, err error)
}

// 通过一个选项实现为一个函数指针来达到一个目的:设置选项中的数据的状态
// Golang函数指针的用法
type Option func(c *options)

// 设置某个参数的一个具体实现,用到了闭包的用法。
// 不仅仅只是设置而采用闭包的目的是为了更为优化,更好用,对用户更友好
func LogError(f func(ctx context.Context, err error)) Option {
    return func(opts *options) {
        opts.logError = f
    }
}

func ConnectionTimeout(d time.Duration) Option {
    return func(opts *options) {
        opts.connectionTimeout = d
    }
}

func WriteTimeout(d time.Duration) Option {
    return func(opts *options) {
        opts.writeTimeout = d
    }
}

func ReadTimeout(d time.Duration) Option {
    return func(opts *options) {
        opts.readTimeout = d
    }
}

// 构造函数具体实现,传入相关Option,new一个对象并赋值
// 如果参数很多,也不需要传入很多参数,只需要传入opts ...Option即可
func NewCluster(opts ...Option) *Cluster {
    clusterOpts := options{}
    for _, opt := range opts {
        // 函数指针的赋值调用
        opt(&clusterOpts)
    }

    cluster := new(Cluster)
    cluster.opts = clusterOpts

    return cluster
}

func main() {

    // 前期储备,设定相关参数
    commonsOpts := []Option{
        ConnectionTimeout(1 * time.Second),
        ReadTimeout(2 * time.Second),
        WriteTimeout(3 * time.Second),
        LogError(func(ctx context.Context, err error) {
        }),
    }

    // 终极操作,构造函数
    cluster := NewCluster(commonsOpts...)

    // 测试验证
    fmt.Println(cluster.opts.connectionTimeout)
    fmt.Println(cluster.opts.writeTimeout)

}

复制代码

本文来自:51CTO博客

感谢作者:mob604756e7db9c

查看原文:Golang面向对象编程之构造函数【struct&new】

相关阅读 >>

一文搞懂 Go 超时控制

Golang 如何处理死锁

聊聊cortex的readring

手撸Golang Go与微服务 saga模式之5

Golang基础-http server

Go 内嵌静态资源

Golang grpc无法安装原因

Go官方文档,我们能得到哪些资料?

Golang怎么判断channel是否关闭

Golang 上传office文档并转化为pdf

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...