GO接口赋值与方法接收者问题

本文探讨了Go语言中接口赋值与方法接收者的关系。以值为接收者的方法,接收者可以是值或指针;而以指针为接收者的方法,接收者必须是指针。通过示例代码解释了为何&test2能赋值给itest但test2不能,原因是传引用与传值的区别。作者鼓励读者讨论和分享不同的见解。
摘要由CSDN通过智能技术生成

这篇博客是受到GO语言中文网论坛中问题启发所写,原链接在此https://studygolang.com/topics/5946

其中第一个回复为博主

有代码如下:

package main

import "fmt"

type TestStruct struct {
	id   int
	name string
}

type AnotherTestStruct struct {
	id   int
	name string
}

type ITest interface {
	SayHello()
}

func main() {
	var itest ITest
	test := TestStruct{id: 1, name: "test1"}
	test2 := AnotherTestStruct{id: 2, name: "anotherTest"}
	itest = test     // OK
	itest.SayHello() // test1

	itest = &test    // OK
	itest.SayHello() // test1

	itest = test2    // cannot use test2 (type AnotherTestStruct) as type ITest in assignment:
				     // AnotherTestStruct does not implement ITest (SayHello method has pointer receiver)
	itest.SayHello()

	itest = &test2	 // OK
	itest.SayHello() // anotherTest
}

func (test TestStruct) SayHello() {
	fmt.Println(tes
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值