this
, self
, me
, etc. The author also encountered similar students in actual project development. Repeated reminders had no effect, so I decided to write this article to persuade these students.
CR Standard Practice
First let’s take a look at the standard naming recommended by GOReceiver Names
. The following content is excerpted from https://github.com/golang/go/wiki/CodeReviewComments #receiver-names:
The name of a method's receiver should be a reflection of its identity; often a one or two letter abbreviation of its type suffices (such as "c" or "cl" for "Client"). Don't use generic names such as "me", "this" or "self", identifiers typical of object-oriented languages that gives the method a special meaning. In Go, the receiver of a method is just another parameter and therefore, should be named accordingly. ...
The simple translation summary has the following 2 points:
The method receiver name should reflect its identity, and do not use
me
,this
,self
are typical identifiers of object-oriented languages.In go, the method receiver is actually another parameter of the method.
Receiver is the first parameter of the method!
The second point above may not be easy to understand, so let’s look at the demo below:
// T ... type T int // Println ... func (t T) Println() { fmt.Println("value: %v", t) } func main() { t := T(1) t.Println() T.Println(t) // receiver作为函数的第一个参数,这个时候发生值拷贝,所以方法内部的t变量是真实t变量的一个拷贝 // 这和this的含义是不相符的 } // output: value: 1 value: 1
通过上面的demo, 我们知道接受者可以直接作为第一个参数传递给方法的。而t.Println()
应该就是Go中的一种语法糖了。
到这里可能有同学又要问了, 既然Go提供了这种语法糖,那我们这样命名有什么问题呢?笔者先不着急解释, 我们继续看下面的demo:
// Test ... type Test struct { A int } // SetA ... func (t Test) SetA(a int) { t.A = a } // SetA1 ... func (t *Test) SetA1(a int) { t.A = a } func main() { t := Test{ A: 3, } fmt.Println("demo1:") fmt.Println(t.A) t.SetA(5) fmt.Println(t.A) t1 := Test{ A: 4, } fmt.Println("demo2:") fmt.Println(t1.A) (&t1).SetA1(6) fmt.Println(t1.A) } // output: demo1: 3 3 demo2: 4 6
看上面的demo我们知道, 当receiver不是指针时调用SetA
其值根本没有改变。
因为Go中都是值传递,所以你如果对SetA的receiver的名称命名为this
, self
等,它就已经失去了本身的意义——“调用一个对象的方法就是向该对象传递一条消息”。而且对象本身的属性也并不一定会发生改变。
综上: 请各位读者在对receiver命名时不要再用this
, self
等具有特殊含义的名称啦。
Receiver是可以为nil的!!!
最近在研读h2_bundle.go
的时候,发现了一段特殊的代码,顿时惊出一身冷汗,姑在本文补充一下,以防止自己和各位读者踩坑。
源代码截图如下:
惊出我一身冷汗的正是图中标红的部分,receiver居然还要判断为nil!在我的潜意识里一直是这样认为的,receiver默认都是有值的,直接使用就行了。这简直颠覆我的认知,吓得我赶紧写了个demo验证一下:
type A struct { v int } func (a *A) test() { fmt.Println(a == nil) } func (a *A) testV() { fmt.Println(a.v) } func main() { var a *A a.test() a.testV() }
上述输出如下:
a.test()
can output normally, but panic is reported only when processing the internal variable v
of the variable structure! ! ! Fortunately, this article has already introduced Receiver is the first parameter
of the method. Because it is the first parameter, even if it is passed as a parameter, the function can be called normally even if it is nil
, and panic will be reported where it is actually used.
The above is the detailed content of Why is it not recommended to use this or self for receiver name in go?. For more information, please follow other related articles on the PHP Chinese website!

Mastering the strings package in Go language can improve text processing capabilities and development efficiency. 1) Use the Contains function to check substrings, 2) Use the Index function to find the substring position, 3) Join function efficiently splice string slices, 4) Replace function to replace substrings. Be careful to avoid common errors, such as not checking for empty strings and large string operation performance issues.

You should care about the strings package in Go because it simplifies string manipulation and makes the code clearer and more efficient. 1) Use strings.Join to efficiently splice strings; 2) Use strings.Fields to divide strings by blank characters; 3) Find substring positions through strings.Index and strings.LastIndex; 4) Use strings.ReplaceAll to replace strings; 5) Use strings.Builder to efficiently splice strings; 6) Always verify input to avoid unexpected results.

ThestringspackageinGoisessentialforefficientstringmanipulation.1)Itofferssimpleyetpowerfulfunctionsfortaskslikecheckingsubstringsandjoiningstrings.2)IthandlesUnicodewell,withfunctionslikestrings.Fieldsforwhitespace-separatedvalues.3)Forperformance,st

WhendecidingbetweenGo'sbytespackageandstringspackage,usebytes.Bufferforbinarydataandstrings.Builderforstringoperations.1)Usebytes.Bufferforworkingwithbyteslices,binarydata,appendingdifferentdatatypes,andwritingtoio.Writer.2)Usestrings.Builderforstrin

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
