zoukankan      html  css  js  c++  java
  • 八、结构体和接口

    结构体定义:

    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()
    
    }
  • 相关阅读:
    nginx nfs服务
    Linux磁盘分区-rpm-yum
    tar命令-vi编辑器-磁盘分区及格式化-软链接及硬链接文件
    Linux命令-权限
    Linux命令基础
    网络基础
    操作系统
    计算机硬件介绍
    Django之CBV和FBV
    ORM之基本操作增删改查
  • 原文地址:https://www.cnblogs.com/wuwangchuxin0924/p/9057903.html
Copyright © 2011-2022 走看看