Golang语言中的method是什么

frankphper · 2019-04-29 16:37:40 · 1002 次点击 · 预计阅读时间 2 分钟 · 大约8小时之前 开始浏览    
这是一个创建于 2019-04-29 16:37:40 的文章,其中的信息可能已经有所发展或是发生改变。

什么是method(方法)?method是函数的另外一种形态,隶属于某个类型的方法。method的语法:func (r Receiver) funcName (parameters) (result)。receiver可以看作是method的第一个参数,method并且支持继承和重写。

/**
 * 什么是method(方法)?method是函数的另外一种形态,隶属于某个类型的方法。
 * method的语法:func (r Receiver) funcName (parameters) (result)。
 * receiver可以看作是method的第一个参数,method并且支持继承和重写。
 */
package main

import (
    "fmt"
)

type Human struct {
    name string
    age  int
}

// 字段继承
type Student struct {
    Human  // 匿名字段
    school string
}
type Employee struct {
    Human   // 匿名字段
    company string
}

// 函数的另外一种形态:method,语法:func (r Receiver) funcName (parameters) (result)
// method当作struct的字段使用
// receiver可以看作是method的第一个参数
// 指针作为receiver(接收者)和普通类型作为receiver(接收者)的区别是指针会对实例对象的内容发生操作,
// 普通类型只是对副本进行操作
// method也可以继承,下面是一个匿名字段实现的method,包含这个匿名字段的struct也能调用这个method
func (h *Human) Info() {
    // method里面可以访问receiver(接收者)的字段
    fmt.Printf("I am %s, %d years old\n", h.name, h.age)
}

// method重写,重写匿名字段的method
// 虽然method的名字一样,但是receiver(接收者)不一样,那么method就不一样
func (s *Student) Info() {
    fmt.Printf("I am %s, %d years old, I am a student at %s\n", s.name, s.age, s.school)
}
func (e *Employee) Info() {
    fmt.Printf("I am %s, %d years old, I am a employee at %s\n", e.name, e.age, e.company)
}
func main() {
    s1 := Student{Human{"Jack", 20}, "tsinghua"}
    e1 := Employee{Human{"Lucy", 26}, "Google"}
    // 调用method通过.访问,就像struct访问字段一样
    s1.Info()
    e1.Info()
}

有疑问加站长微信联系(非本文作者))

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1002 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传