The types defined in the Golang program have methods associated with them. Let's take a look at an example: "' Gotype T struct {name String}func (T T) printname () {fmt. Println (T.name)}func main () {t: = t{name: "Michał"} T.printname ()} "" As you may suspect the program output name. A method is a function that has a parameter list of additional, individual elements, called sinks. It is placed before a method name. The type of receiver determines how the method is used. The # # Receiver method is bound to the base class of the sink. The small example explains well: the code above "Gotype T struct {name String}func (t) f () {}func (*t) F () {}" cannot be compiled. The first F method is bound to T. The second method was *t on the state. For a single base type, the method name must be unique, so the compilation will be error: ' ' > Go install github.com/mlowicki/lab &&./spec/bin/l ab# Github.com/mlowicki/labspec/src/github.com/mlowicki/lab/lab.go:103:method Redeclared:t.f Method (T) func () Method (*t) func () "If the base class is a struct type, then the field name cannot be duplicated with the method name. "' Gotype t struct {m int}func (T T) m () {}" "Compilation failure information is as follows: ' ' Type T has both field and method named M ' Go type system limits which types can be Receiver. It cannot be an interface type or pointer, so it is not possible to define methods for an empty interface (interface{}) to satisfy all types. only allows the use of type names, so literal literals cause compilation errors: ' ' Gofunc (v map[string]float64) M () {} ' error message ' invalid receiver type map[string] Float64 (Map[string]float64 is a unnamed type). ' # # Method set calls M method on a variable of type T, method m Must be on the set of methods associated with T. What does a member of the method set mean? # # # Interface Type the method set of the interface type is the interface itself-a list of methods for implementing the interface needs to be defined: ' ' Gotype I interface {F () G ()}type T struct{}func (t) F () {}func (t ) G () {}func (T) H () {}func main () {var i i = t{} i.f () I.G () I.H ()//error:i.h undefined (Type I has no field or Metho D H)} ' in the above example, the method on the variable I of type T is not allowed to be called. Only the interface type value method from the interface is part of the method set of the interface type. (The set of methods is static and does not change when assigning values of different types). To invoke the H method, you need to first use the type assertion: "' Got, OK: = i. (T) if!ok {log. Fatal ("type assertion failed")}t.h () "# # # of non-interface types for non-interface type T, the set of methods consists of methods of the receiver T: ' ' Gotype t Struct{}func (t) F () {}func (T) G () {}type U struct{}func (u) H () {}func main () {t: = t{} t.f () t.g () T.H ()//error:t.h undefined (type T has field or Method H)} ' when dealing with a pointer of type T, its set of methods consists of a receiver T or *t method: ' Gotype t Struct{}func (t) F () {}func (T) G () {}func (*t) H () {}func Main () {t: = &t{} t.f () t.g () T.H ()} "Why is the method set of T not a method of *t type sink, and the *t method set contains the method of the T type receiver? Surprisingly, the assignment to T is not an address, but the no pointer structure value still performs well: ' ' Got: = T{}t.f () t.g () T.H () ' Go specification describes the explicit case:> if X is addressable and the method set of X contains M, X.M () Yes (& x). Shorthand for M (). When to use a value orThe recommendations for the pointer receiver are placed in the official [FAQ] (https://golang.org/doc/faq#methods_on_values_or_pointers). # # # Unique type T defines a set of methods that cannot have two names. Having the same method name but different types of parameters is not possible in Go. (There is no [ad hoc polymorphism] (https://en.wikipedia.org/wiki/Ad_hoc_polymorphism) in Go.) The set of methods defined by the > type T is implemented by T. # # Printing method Set Go has a [reflect] (https://golang.org/pkg/reflect/) package, which is useful for viewing the set of methods for a type: "' Gofunc printmethodset ( Val interface{}) {t: = reflect. TypeOf (Val) fmt. Printf ("Number of methods:%d\n", T.nummethod ()) for I: = 0; I < T.nummethod (); i++ {m: = T.method (i) fmt. Printf ("Method%s\n", m) fmt. Printf ("\tname:%s\n", M.name) fmt. Printf ("\tpackage Path:%s\n", M.pkgpath)} "returns a value type from [Method] (https://golang.org/pkg/reflect/#Value. method) by [ Method] (https://golang.org/pkg/reflect/#Method) type. It is worth mentioning that the document has a bug because [Nummethod] (https://golang.org/pkg/reflect/ #Value. Nummethod) Returns the number of methods from the method set, but only those methods that are exported (the first name begins with a capital letter). Archived in [#17686] (https://github.com/golang/go/issues/17686). # # Introduction Type method methods can only be defined in packages that have type creation. Github.com/mlowicki/lib/lib.go: ' Gopackage libtype T struct{} ' giThub.com/mlowicki/lab/lab.go: "Gopackage mainimport (" FMT "). "Github.com/mlowicki/lib") func (T) F () {}func (*t) F () {}[...] "This will cause build errors ' cannot define new methods on Non-local type lib. T '. # # does not use the parameter function/method definition to not enforce naming of all parameters or receivers. If you do not use them, you can specify only the type. Name can eventually introduced later on when it ' ll actually needed: ' Gotype T struct {name String}func (T t) F (name s Tring) {}func (T) g (string) {} "G" declaration omits the useless identifier.
via:https://medium.com/golangspec/methods-in-go-part-i-a4e575dff860
Author: Michałłowicki Translator: themoonbear proofreading: polaris1119
This article by GCTT original compilation, go language Chinese network honor launches
This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove
146 Reads