Golang学习笔记

2017-11-17

go变量声明与C语言的不同: go变量声明引入var关键字可以一次同时声明多个变量 var myvar1, myvar2, myvar3 int OR var ( myvar1 int myvar2 string ) 变量类型声明与C类似,类型关键字在

Read More…

Golang Tips

2017-11-17

How to write customized error with optional error struct passed type Y2HError struct { errMsg string errDetail error } func (e *Y2HError) Error() string { if e.errDetail != nil { return e.errMsg + "\n-------------------\n" + e.errDetail.Error() } return e.errMsg } func NewY2HError(errMsg string, errSlice ...error) *Y2HError { var errDetail error = nil if len(errSlice) == 1 { errDetail = errSlice[0] } return &Y2HError{errMsg, errDetail} } How to do generic type checking Use reflect package to get TypeOf(object)

Read More…

Golang OOP

2017-11-17

How to simiuate super.init() in Python type Baser interface { Init(name string) Do() } type BaseClass struct { name string } func (cls *BaseClass) Init(name string) { cls.name = name } type SepcificClass struct { BaseClass } func (cls *SpecificClass) Init(name string) { cls.BaseClass.Init(name) } func main() { var cls *specificClass cls = &SpecificClass{} cls.Init("ryan") } How to automacially init base class’s instance value type Baser interface { Do() } type BaseClass struct { name string } func (cls *BaseClass) Do() { } type SepcificClass struct { BaseClass } func (cls *SepcificClass) Do() { } // the explict way to initialize base class's value func (cls *SpecificClass) New1() Baser { return &SepcificClass{ BaseClass{"ryan"} } } func (cls *SpecificClass) New2() Baser { instance := &SepcificClass{} instance.

Read More…