面向对象(Methods, Interfaces)

Method

method是附属在一个给定的类型上的,他的语法和函数的声明语法几乎一样,只是在func后面增加了一个receiver(也就是method所依从的主体)。

语法

func (r ReceiverType) funcName(parameters) (results)

示例

type rectangle struct {
width float64
heigth float64
} func (receiver rectangle) area() float64 {
return receiver.width * receiver.heigth
} func main(){
rect := rectangle{heigth: 12, width: 12}
area := rect.area()
fmt.Println(area)
}

注意

  • 接收者不一样,那么method就不一样
  • method里面可以访问接收者的字段
  • 调用method通过.访问,就像struct里面访问字段一样
  • 定义在任何你自定义的类型、内置类型、struct等各种类型上面
  • 如果想要改变接受者的内容,可以使用指针

interface

简单的说,interface是一组method签名的组合,我们通过interface来定义对象的一组行为

/* 定义接口 */
type interface_name interface {
method_name1 [return_type]
method_name2 [return_type]
method_name3 [return_type]
...
method_namen [return_type]
} /* 定义结构体 */
type struct_name struct {
/* variables */
} /* 实现接口方法 */
func (struct_name_variable struct_name) method_name1() [return_type] {
/* 方法实现 */
}
...
func (struct_name_variable struct_name) method_namen() [return_type] {
/* 方法实现*/
}

interface类型定义了一组方法,如果某个对象实现了某个接口的所有方法,则此对象就实现了此接口。

type Isay interface {
say(word string) string
} type dog struct {
name string
} type cat struct {
sex string
} func (d dog) say(word string) string {
return d.name + word
} func (c cat) say(word string) string {
return "cat=" + word
} //使用
var idg, icat Isay
idg = dog{"dog"}
fmt.Println(idg.say("hello"))
icat = cat{"0"}
fmt.Println(icat.say("world"))

最后,任意的类型都实现了空interface(我们这样定义:interface{}),也就是包含0个method的interface。

类型判断

Comma-ok断言

Go语言里面有一个语法,可以直接判断是否是该类型的变量: value, ok = element.(T),这里value就是变量的值,ok是一个bool类型,element是interface变量,T是断言的类型。

如果element里面确实存储了T类型的数值,那么ok返回true,否则返回false。

package main

import (
"fmt"
"strconv"
) type Element interface{}
type List [] Element type Person struct {
name string
age int
} //定义了String方法,实现了fmt.Stringer
func (p Person) String() string {
return "(name: " + p.name + " - age: "+strconv.Itoa(p.age)+ " years)"
} func main() {
list := make(List, 3)
list[0] = 1 // an int
list[1] = "Hello" // a string
list[2] = Person{"Dennis", 70} for index, element := range list {
if value, ok := element.(int); ok {
fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
} else if value, ok := element.(string); ok {
fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
} else if value, ok := element.(Person); ok {
fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
} else {
fmt.Printf("list[%d] is of a different type\n", index)
}
}
}

if-else过多,可以使用switch代替

package main

import (
"fmt"
"strconv"
) type Element interface{}
type List [] Element type Person struct {
name string
age int
} //打印
func (p Person) String() string {
return "(name: " + p.name + " - age: "+strconv.Itoa(p.age)+ " years)"
} func main() {
list := make(List, 3)
list[0] = 1 //an int
list[1] = "Hello" //a string
list[2] = Person{"Dennis", 70} for index, element := range list{
switch value := element.(type) {
case int:
fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
case string:
fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
case Person:
fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
default:
fmt.Println("list[%d] is of a different type", index)
}
}
}

这里有一点需要强调的是:element.(type)语法不能在switch外的任何逻辑里面使用,如果你要在switch外面判断一个类型就使用comma-ok

go学习笔记-面向对象(Methods, Interfaces)的更多相关文章

  1. 0030 Java学习笔记-面向对象-垃圾回收、(强、软、弱、虚)引用

    垃圾回收特点 垃圾:程序运行过程中,会为对象.数组等分配内存,运行过程中或结束后,这些对象可能就没用了,没有变量再指向它们,这时候,它们就成了垃圾,等着垃圾回收程序的回收再利用 Java的垃圾回收机制 ...

  2. 0028 Java学习笔记-面向对象-Lambda表达式

    匿名内部类与Lambda表达式示例 下面代码来源于:0027 Java学习笔记-面向对象-(非静态.静态.局部.匿名)内部类 package testpack; public class Test1{ ...

  3. 0025 Java学习笔记-面向对象-final修饰符、不可变类

    final关键字可以用于何处 修饰类:该类不可被继承 修饰变量:该变量一经初始化就不能被重新赋值,即使该值跟初始化的值相同或者指向同一个对象,也不可以 类变量: 实例变量: 形参: 注意可以修饰形参 ...

  4. 0013 Java学习笔记-面向对象-static、静态变量、静态方法、静态块、单例类

    static可以修饰哪些成员 成员变量---可以修饰 构造方法---不可以 方法---可以修饰 初始化块---可以修饰 内部类(包括接口.枚举)---可以修饰 总的来说:静态成员不能访问非静态成员 静 ...

  5. C#学习笔记——面向对象、面向组件以及类型基础

    C#学习笔记——面向对象.面向组件以及类型基础 目录 一 面向对象与面向组件 二 基元类型与 new 操作 三 值类型与引用类型 四 类型转换 五 相等性与同一性 六 对象哈希码 一 面向对象与面向组 ...

  6. 程序设计基础·Java学习笔记·面向对象(上)

    Java程序设计基础之面向对象(上) (自适应学习进度而进行记录的笔记,希望有一些小小的用处吧(^∀^●)ノシ) (新人上路,望多指教,如有错误,望指正,万分感谢(o゚v゚)ノ) 目录 一.面向对象 ...

  7. 程序设计基础·Java学习笔记·面向对象(下)

    Java程序设计基础之面向对象(下) (补充了上的一些遗漏的知识,同时加入了自己的笔记的ヾ(•ω•`)o) (至于为什么分P,啊大概是为了自己查笔记方便(?)应该是("` 3′") ...

  8. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(九)之Interfaces

    Interfaces and abstract classes provide more structured way to separate interface from implementatio ...

  9. JavaScript学习笔记-面向对象的模块化编程

    面向对象的模块化编程 模块是一个独立的JS文件,模块文件可以包含一个类定义.一组相关的类.一个实用函数库.一些待执行的代码 模块化的目标:支持大规模的程序开发,处理分散源代码的组装,并能让代码正确执行 ...

随机推荐

  1. 关于使用metronic时里modal模拟框使用ueditor时不能全屏的情况

    ueditor里有这么断代码, 1.初始显示状态下(非全屏),修改一下代码的z-index UE.Editor.defaultOptions = function(editor){ var _url ...

  2. 华为OJ-表示数字

    要求:将一个字符中所有出现的数字前后加上符号"*",其他字符保持不变 #include<iostream> #include<string> using n ...

  3. POJ-2886 Who Gets the Most Candies?---线段树+约瑟夫环

    题目链接: https://cn.vjudge.net/problem/POJ-2886 题目大意: N个人围成一圈第一个人跳出圈后会告诉你下一个谁跳出来跳出来的人(如果他手上拿的数为正数,从他左边数 ...

  4. Android(java)学习笔记42:Map集合的获取功能

    1. Map集合的获取功能:  package cn.itcast_01; import java.util.Collection; import java.util.HashMap; import ...

  5. html题型

    1.doctype的意义是什么 这个是有历史背景的,在很久以前,IE有一些自己的渲染模式,最典型的就是盒子模型,包括边距.这就造成了不兼容模式,所以他的意义 1)让浏览器以标准模式渲染 2)让浏览器知 ...

  6. 【转】android Looper 理解

    在主线程中运行的部分,都可以直接使用Handler,因为在主线程启动的过程中(ActivityThread的main函数里)会调用Looper.prepareMainLooper(),Looper类中 ...

  7. JAVA程序员常用软件类库下载地址整理

    IT行业是个发展更新特别快的领域,每个程序员在职业生涯中都会经历各类技术和工具的更新迭代. 俗话说:工欲善其事,必先利其器.本着独乐乐不如众乐乐的精神(其实是自己健忘)本人把经常要用到的软件工具官方下 ...

  8. 使用vue自定义组件以及动态时间

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  9. java递归菜单树转换成pojo对象

    package com.cjonline.foundation.authority.pojo; import java.util.ArrayList; import java.util.Collect ...

  10. CodeForces - 598A Tricky Sum (数学,快速幂的运用)

    传送门: http://codeforces.com/problemset/problem/598/A A. Tricky Sum time limit per test 1 second memor ...