golang中的指针方法和值方法的区别,编程时该如何选择呢?

这篇具有很好参考价值的文章主要介绍了golang中的指针方法和值方法的区别,编程时该如何选择呢?。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1 方法

我们都知道,方法的接收者类型必须是某个自定义的数据类型,而且不能是接口类型或接口的指针类型。所谓的值方法,就是接收者类型是非指针的自定义数据类型的方法。

package main

import "fmt"

type Cat struct {
	Name string
}

func (c Cat) SetName(s string) {
	c.Name = s
}

func (c Cat) GetName() string {
	return c.Name
}

func (c *Cat) SetNameV2(s string) {
	c.Name = s
}

func (c *Cat) GetNameV2() string {
	return c.Name
}

func main() {
	var c1, c2 Cat
	c1.SetName("cat1")                     // 等价于 (&c1).SetName("cat1")
	c2.SetNameV2("cat2")                   // 等价于 (&c2).SetNameV2("cat2")
	fmt.Printf("c1: %s\n", c1.GetName())   // ""
	fmt.Printf("c2: %s\n", c2.GetNameV2()) // "cat2"

	var c3, c4 *Cat
	c3 = &Cat{}
	c4 = &Cat{}
	c3.SetName("cat3")
	c4.SetNameV2("cat4")
	fmt.Printf("c3: %s\n", c3.GetName())   // ""
	fmt.Printf("c4: %s\n", c4.GetNameV2()) // "cat4"
}

值方法和指针方法使用技巧

Choosing whether to use a value or pointer receiver on methods can be difficult, especially to new Go programmers. If in doubt, use a pointer, but there are times when a value receiver makes sense, usually for reasons of efficiency, such as for small unchanging structs or values of basic type. Some useful guidelines:文章来源地址https://www.toymoban.com/news/detail-486760.html

  • If the receiver is a map, func or chan, don’t use a pointer to them. If the receiver is a slice and the method doesn’t reslice or reallocate the slice, don’t use a pointer to it.
  • If the method needs to mutate the receiver, the receiver must be a pointer.
  • If the receiver is a struct that contains a sync.Mutex or similar synchronizing field, the receiver must be a pointer to avoid copying.
  • If the receiver is a large struct or array, a pointer receiver is more efficient. How large is large? Assume it’s equivalent to passing all its elements as arguments to the method. If that feels too large, it’s also too large for the receiver.
  • Can function or methods, either concurrently or when called from this method, be mutating the receiver? A value type creates a copy of the receiver when the method is invoked, so outside updates will not be applied to this receiver. If changes must be visible in the original receiver, the receiver must be a pointer.
  • If the receiver is a struct, array or slice and any of its elements is a pointer to something that might be mutating, prefer a pointer receiver, as it will make the intention clearer to the reader.
  • If the receiver is a small array or struct that is naturally a value type (for instance, something like the time.Time type), with no mutable fields and no pointers, or is just a simple basic type such as int or string, a value receiver makes sense. A value receiver can reduce the amount of garbage that can be generated; if a value is passed to a value method, an on-stack copy can be used instead of allocating on the heap. (The compiler tries to be smart about avoiding this allocation, but it can’t always succeed.) Don’t choose a value receiver type for this reason without profiling first.
  • Don’t mix receiver types. Choose either pointers or struct types for all available methods.
  • Finally, when in doubt, use a pointer receiver.

Reference

  1. https://crazyjums-1.gitbook.io/36-lectures-on-golang/13-jie-gou-ti-ji-qi-fang-fa-de-shi-yong-fa-men
  2. https://zhuanlan.zhihu.com/p/101363361
  3. https://github.com/golang/go/wiki/CodeReviewComments#receiver-type

到了这里,关于golang中的指针方法和值方法的区别,编程时该如何选择呢?的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • python中的os.mkdir和os.makedirs的使用区别,以及如何查看某个模块中的某些字母开头的属性方法

    os.mkdir(dir_name) :用于 新建文件夹 ,当要新建的文件夹已经存在的时候,就会报错: FileExistsError: [Errno 17] File exists: 因此,我们一般在新建一个文件夹的时候,会和 os.path.exists() 集合使用,如下: 1、判断一个 文件夹是否存在 ,如果不存在就新建它,如果已经存在就跳过:

    2023年04月08日
    浏览(39)
  • 【当LINUX系统出现网络问题时该如何排查】

    因为网络问题产生的现象有无数种,但同一种现象的产生并不一定是由于网络问题引起的。比如页面卡顿,数据包无法处理这些现象,完全有可能是死锁或者进程异常终止产生的。 所以,结论不要下的太早,先问问自己,网络问题是什么,是不通,还是慢?现象是什么?一步

    2024年02月04日
    浏览(26)
  • 【Go进阶】详解方法的值类型和指针类型区别

    目录 值类型和指针类型 方法也有值类型的方法和指针类型的区别 ,也就是以下两种receiver: setname()方法中是值类型的receiver,setage()方法中是指针类型的receiver。它们是有区别的。 首先,setage()方法的p是一个指针类型的person实例,所以方法体中的 p.age 实际上等价于 (*p).age 。

    2023年04月10日
    浏览(31)
  • 【线程池】面试被问到线程池参数如何配置时该如何回答

           前言         没有基于业务场景,直接抛出这个问题,等同于耍流氓。         八股文告诉我们CPU密集型就 核心数+1 ,IO密集型就 核心数*2 ,那么真实业务中该怎么去配置呢。         方法论还是有的         1.需要分析线程池执行的任务的特性: CPU 密集型

    2024年02月09日
    浏览(37)
  • 当软件测试迭代测试时间不够时该如何去做好质量控制呢?

    大家好,今天我们一起来聊聊,当我们在工作中尤其是快速迭代版本中测试版本的时间被压缩的很短,甚至不够完成用例执行时怎么去做好质量控制呢? 在我们的日常生活中导致软件测试时间不够的原因有很多,那么在这些不确定的人为因素中如何去做好呢? 1、需求层面:

    2024年02月10日
    浏览(44)
  • 【Golang星辰图】数据管理利器:Go编程语言中的数据库和搜索引擎综合指南

    Go编程语言是一种强大、类型安全且高效的编程语言,它在处理数据库和搜索引擎方面有着广泛的应用。本篇文章将详细介绍几个Go编程语言中常用的数据库和全文搜索引擎,包括Go-bleve、Go-pgx、Go-leveldb/leveldb、Go-xorm、Go-mysql-driver和Go-bbolt/bbolt。对于每个工具,我们将介绍其功

    2024年03月26日
    浏览(48)
  • 快慢指针该如何操作?本文带你认识快慢指针常见的三种用法及在链表中的实战

    很多同学都听过 快慢指针 这个名词,认为它不就是定义两个引用(指针)一前一后吗?是的,它的奥秘很深,它的作用究竟有哪些?究竟可以用来做哪些题目?下面我将一一带你了解和应用 下面的本节的大概内容,有疑惑的点,欢迎小伙伴们留言 目录 1.简述快慢指针 2.快慢

    2024年02月04日
    浏览(28)
  • c语言编程中出现错误: 表达式必须包含指向对象的指针类型。 该错误如何解决? 下文解答

    表达式必须包含指向对象的指针类型,但他具有类型\\\"int\\\" 具体原因是因为arr数组本质是一个指针类型,指向的是首元素的地址,如果用int 来接收显然不合适,以至于在引用下列定义的int类型的变量时候产生错误——表达式必须包含指向对象的指针类型,但他具有类型\\\"int\\\",解决

    2024年02月11日
    浏览(33)
  • golang学习-指针

    1、定义 指针也是一个变量,但它是一个特殊的变量,它存储的是另一个变量的内存地址。是引用数据类型。 取一个变量的地址:a  定义: var p *int = a 可以理解为 指针变量p中存储的是a的内存地址,但是变量p也有自己的内存地址。 2、指针取值 *p 表示的是 取出p这个变量对

    2024年02月02日
    浏览(30)
  • Golang指针详解

    要搞明白Go语言中的指针需要先知道3个概念:指针地址、指针类型和指针取值。 我们知道变量是用来存储数据的,变量的本质是给存储数据的内存地址起了一个好记的别名。比如我们定义了一个变量 a := 10 ,这个时候可以直接通过 a 这个变量来读取内存中保存的 10 这个值。

    2024年02月15日
    浏览(35)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包