因为go和传统的面向对象的编程语言不太一样,没有什么类和继承的概念.通过接口来实现面向对象。
- 而go的类也就是结构体
- 所以索性就放在一起讲了
- interface(接口)是golang最重要的特性之一,Interface类型可以定义一组方法,但是这些不需要实现。
请注意:此处限定是一组方法,既然是方法,就不能是变量。
而且是一组,表明可以有多个方法。
package mainimport "fmt"type Map struct {w,h float64
}func increase(_map Map) float64 {_map.w = 10_map.h = 10return _map.w * _map.h
}// 定义结构体扩充的方法, 相当于js的prototype
func (_map Map) getProduct() float64 {return _map.w * _map.h
}type DBInstance interface {}
// interface多态定义未实现的方法, 相当于java的interface接口(定义规范)
type DBConn interface {getInstance(driverName string) DBInstanceinsert(sql string) // void 无返回值query(sql string) []map[string]stringupdate(sql string)delete(sql string)
}// go通过struct实现interface
type mySql struct {}func (mysql *mySql) getInstance(driverName string) DBInstance {panic("implement me")
}func (mysql *mySql) query(sql string) []map[string]string {panic("implement me")
}func (mysql *mySql) update(sql string) {panic("implement me")
}func (mysql *mySql) delete(sql string) {panic("implement me")
}// 实现interface
func (mysql *mySql)insert(sql string) {fmt.Println(sql)fmt.Println("do insert somethings to mysql database...")
}// go通过struct实现interface
type postgres struct {}
// 实现interface
func (pgSql *postgres)insert(sql string) {fmt.Println(sql)fmt.Println("do insert somethings to postgres database...")
}func main() {var _map = Map{w: 5, h: 5}// go使用指针改变传递进来变量的值// go是值传递var product = increase(_map) // product: 乘积fmt.Println("product = ",product)fmt.Println("go是值传递: ", _map.w, _map.h)fmt.Println("---------------------------------------")// ---------------------------------------// go结构体函数fmt.Println("结构体函数: product = ", _map.getProduct())fmt.Println("---------------------------------------")// ---------------------------------------var mysqlConn DBConn_mySql := mySql{}mysqlConn = &_mySqlmysqlConn.insert("insert into table username = user1")
}