Golang method overriding examples

Prior Knowledge

  1. Pointer and Value Receiver
package main

type V struct{}

func (*V) method() {}

func main() {
	var v V
	v.method() // This is also correct.
	p := &v
	p.method() // No problem.
}

Methods with pointer receivers can take either a value or a pointer as the receiver.
Methods and pointer indirection

package main

type V struct{}

func (V) method() {}

func main() {
	var v V
	v.method() // No problem.
	p := &v
	p.method() // This is also correct.
}

Methods with value receivers can take either a value or a pointer as the receiver.
Methods and pointer indirection (2)

Notes: Don’t be confused with “Which one implements the interface? Pointer or Value receiver?”. They are totally different things.


  1. Structs and embedding (from golang specification)

Given a struct type S and a defined type T, promoted methods are included in the method set of the struct as follows:

  • If S contains an embedded field T, the method sets of S and *S both include promoted methods with receiver T. The method set of *S also includes promoted methods with receiver *T.
  • If S contains an embedded field *T, the method sets of S and *S both include promoted methods with receiver T or *T.

Code Example

Exercise (experiment):

package main

import (
	"fmt"
)

type base struct{}

func (*base) hello() {
	fmt.Println("hello from base")
}

type derived struct {
	base
}

func (derived) hello() {
	fmt.Println("hello from derived")
}

func main() {
	b := base{}
	b.hello()

	d := &derived{}
	d.hello()
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值