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

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

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


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

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)
}


相关文章
|
1月前
|
Go
golang中make 和 new 的区别
golang中make 和 new 的区别
20 0
|
2月前
|
安全 Java 编译器
第十一章 Golang面向对象编程(下)
第十一章 Golang面向对象编程(下)
43 2
|
2月前
|
存储 Go
Golang里空结构体struct{}的介绍和使用
【2月更文挑战第10天】Golang里空结构体struct{}的介绍和使用
39 6
|
7月前
|
安全 Go
Golang 语言是面向对象编程风格的编程语言吗?
Golang 语言是面向对象编程风格的编程语言吗?
25 0
|
11天前
|
Go
golang中置new()函数和make()函数的区别
golang中置new()函数和make()函数的区别
|
16天前
|
Go 开发者
Golang深入浅出之-Go语言方法与接收者:面向对象编程初探
【4月更文挑战第22天】Go语言无类和继承,但通过方法与接收者实现OOP。方法是带有接收者的特殊函数,接收者决定方法可作用于哪些类型。值接收者不会改变原始值,指针接收者则会。每个类型有相关方法集,满足接口所有方法即实现该接口。理解并正确使用这些概念能避免常见问题,写出高效代码。Go的OOP机制虽不同于传统,但具有灵活性和实用性。
23 1
|
16天前
|
Go 开发者
Golang深入浅出之-Go语言结构体(struct)入门:定义与使用
【4月更文挑战第22天】Go语言中的结构体是构建复杂数据类型的关键,允许组合多种字段。本文探讨了结构体定义、使用及常见问题。结构体定义如`type Person struct { Name string; Age int; Address Address }`。问题包括未初始化字段的默认值、比较含不可比较字段的结构体以及嵌入结构体字段重名。避免方法包括初始化结构体、自定义比较逻辑和使用明确字段选择器。结构体方法、指针接收者和匿名字段嵌入提供了灵活性。理解这些问题和解决策略能提升Go语言编程的效率和代码质量。
29 1
|
2月前
|
程序员 Go
第十章 Golang面向对象编程(上)
第十章 Golang面向对象编程(上)
40 2
|
6月前
|
存储 Go
Golang中的New和Make:内存分配与初始化的区别
摘要:本文将深入探讨Golang中的New和Make函数在内存分配和初始化方面的区别。我们将通过理论阐述和示例代码来解释这两个函数的作用,并帮助读者更好地理解它们在实际编程中的应用。
|
7月前
|
JSON Go 数据格式
Golang 语言 Struct 中字段的 Tag 怎么使用?
Golang 语言 Struct 中字段的 Tag 怎么使用?
30 0