八、结构体和接口

结构体定义:

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