八、结构体和接口
发布时间:2020-12-16 09:35:30 所属栏目:大数据 来源:网络整理
导读:结构体定义: 和 C++? 一样, Golang 的结构体也是封装数据。可以说是面向对象吧。 结构体的组合函数: package main import ( "fmt" ) type Node struct { x,y int } // 结构体外接函数(能不能在结构体内写,目前还不清楚能不能在内部定义 func (node Node
结构体定义: 和C++?一样,Golang的结构体也是封装数据。可以说是面向对象吧。 结构体的组合函数: package main import ( "fmt" ) type Node struct { x,y int } // 结构体外接函数(能不能在结构体内写,目前还不清楚能不能在内部定义 func (node Node) area() (res int) { res = 0 res = node.x * node.y return } func main() { var node = Node{1,2} fmt.Println(node.area()) } ? 结构体可以内嵌结构体类型的数据 接口: 和C++?的虚函数类似(实现机制目前还不清楚) package main import ( "fmt" ) // 定义接口 type Phone interface { // 定义方法 call() } type Iphone struct { } type Nokiaphone struct { } func (nokiaphone Nokiaphone) call() { fmt.Println("this is Nokiaphone") } func (iphone Iphone) call() { fmt.Println("this is Iphone") } func main() { var phone Phone phone = new(Iphone) phone.call() phone = new(Nokiaphone) phone.call() } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |