method在golang中的作用是什么

发布时间:2021-01-06 15:10:16 作者:Leah
来源:亿速云 阅读:131

这篇文章将为大家详细讲解有关method在golang中的作用是什么,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

什么是method(方法)?method是函数的另外一种形态,隶属于某个类型的方法。

method的语法:

func (r Receiver) funcName (parameters) (result)

receiver可以看作是method的第一个参数,method并且支持继承和重写。

go version go1.12

/**
 * 什么是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()
}

关于method在golang中的作用是什么就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. Method Swizzling对Method的要求是什么
  2. golang中map的作用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

golang method

上一篇:vscode添加背景图的操作步骤

下一篇:利用springboot2.x怎么解决Bean对象注入顺序的问题

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》