面向对象(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

最新文章

  1. FileStream读写文件【StreamWriter 和 StreamReader】
  2. 用.net 发送邮件
  3. ngx_image_thumb模块生成缩略图
  4. 什么是web service
  5. DBConfigReader.java
  6. Android组件Spinner使用
  7. linux上ln链接命令详细说明
  8. Redis "MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk"问题的解决
  9. 有些方法为什么会声明称static静态的
  10. linux更改shell
  11. Animate自定义动画
  12. UVA 1451 Average
  13. 计蒜客:Entertainment Box
  14. 设置mac笔记本为固定ip
  15. pytoch word_language_model 代码阅读
  16. Installing OpenSSH from the Settings UI on Windows Server 2019 or Windows 10 1809
  17. 【转】每天一个linux命令(22):find 命令的参数详解
  18. Ubuntu 16.04 64位 tftp服务器搭建
  19. .NET 垃圾回收机制要点整理
  20. MySQL Connector/NET 使用小结(踩坑之路)

热门文章

  1. 使用mysql5.7新特性解决前通配符查询性能问题
  2. msysGit删除github文件
  3. asp.net超过字数限制用省略号...表示
  4. OC @protocol(声明协议 )
  5. typescript import需要注意的地方以及一点疑问
  6. @Modules( ... ) 多个包路径问题
  7. bootstrap table通过ajax获取后台数据展示在table
  8. maven的.m2文件夹
  9. mybatis学习记录四——输入、输出映射
  10. mybatis学习记录二——mybatis开发dao的方法