首页 > 其他 > 详细

八、结构体和接口

时间:2018-05-18 20:59:16      阅读:203      评论:0      收藏:0      [点我收藏+]

结构体定义:

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

}

 

八、结构体和接口

原文:https://www.cnblogs.com/wuwangchuxin0924/p/9057903.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!