Golang:使用reflect探究struct成员方法接收者指针

本文探讨了Go语言中struct方法接收者为指针和值的区别,包括对字段值修改的影响、方法包含及接口实现。通过示例代码展示了receiver类型如何影响方法调用和接口实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题背景

Go语言的面向对象在概念上与java大同小异,但是由于Go语言在给struct添加method的时候需有一个显示的接收者(receiver),receiver可以是指针类型或是struct的形参,二者到底有啥区别是在学习Go面向对象内容时最容易糊涂的地方。


问题描述

为了更好的阐述问题,首先撸上一段小代码:

//定义一个名为Controller的类
type Controller struct {
    domain string
    count  int
}

//给Controller添加第一个成员方法firstFunc
func (c *Controller) firstFunc(domain string, count int) {
    c.domain = domain
    c.count = count
    fmt.Println("firstFunc's domain is "+c.domain+" count is ", c.count)
}

//给Controller添加第二个成员方法secondFunc
func (c Controller) secondFunc(domain string, count int) {
    c.domain = domain
    c.count = count
    fmt.Println("secondFunc's domain is "+c.domain+" count is ", c.count)
}

如上,在Go中定义类用struct类型,在Controller类有两个field,分别为domiancount,还添加了两个方法,分别是firstFun

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值