面向对象(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. Flask中数据库关联与分页与cache缓存(十二)

    1 一对多(One To Many) 表示一对多的关系时,在子表类 Post 中需要通过 foreign key (外键)引用父表类 User 在Post类中指定ForeignKey: class P ...

  2. YUV数据详解

    http://www.cnblogs.com/azraelly/archive/2013/01/01/2841269.html YUV格式有两大类:planar和packed.对于planar的YUV ...

  3. Using nxlog4go for Testing Environment

    nxlog4go is very simple to use without any configuring, setting. For example: package main import ( ...

  4. CRUD全栈式编程架构之数据层的设计

    CodeFirst 一直以来我们写应用的时候首先都是创建数据库 终于在orm支持codefirst之后,我们可以先建模. 通过模型去创建数据库,并且基于codefirst可以实现方便的 实现数据库迁移 ...

  5. 【转载】#438 - Benefits of Using Interfaces

    You might wonder why you'd define an interface, have a class implement that interface and then acces ...

  6. UVA515 King

    嘟嘟嘟 题目翻译:有n个数,m个限制条件.每一个限制条件形如:1.x y gt c:表示ax + ax+1 + … +ay > c.2.x y It c:表示ax + ax+1 + …… +ay ...

  7. 如何使用MiniProfiler(附最新版MiniProfiler使用心得)

    MiniProfiler这个工具早就久仰大名,不过之前一直没有动力去用,正好最近手上有个ASP.NET MVC的项目,正好拿来试试手,下面是使用最新的4.0.138版本的心得体会以及踩到一些小坑的解决 ...

  8. python time模块计算程序耗时

    import time start = time.clock() end = time.clock() consume_time = end - start

  9. NTU Long-Term Positioning Dataset

    NTU Long-Term Positioning Dataset 地址:http://www.clarenceliang.com/dataset/ 場景:NTU 博理館外廣場 描述:超過一個月連續拍 ...

  10. Android学习笔记_58_清除手机应用程序缓存

    通过查看手机设置(setting)源代码,发现它里面获取应用大小和缓存大小是通过PackageManager里面的getPackageSizeInfo方法.然而此方法时私有的,因此通过反射调用此方法. ...