Function declaration syntax: things in parenthesis before function name

前端 未结 2 1874
醉话见心
醉话见心 2021-01-29 18:22

I\'m sorry I couldn\'t be more specific in the question title, but I was reading some Go code and I encountered function declarations of this form:

func (h handle         


        
2条回答
  •  野性不改
    2021-01-29 18:55

    It means ServeHTTP is not a standalone function. The parenthesis before the function name is the Go way of defining the object on which these functions will operate. So, essentially ServeHTTP is a method of type handler and can be invoked using any object, say h, of type handler.

    h.ServeHTTP(w, r)
    

    They are also called receivers. There are two ways of defining them. If you want to modify the receiver use a pointer like:

    func (s *MyStruct) pointerMethod() { } // method on pointer
    

    If you dont need to modify the receiver you can define the receiver as a value like:

    func (s MyStruct)  valueMethod()   { } // method on value
    

    This example from Go playground demonstrates the concept.

    package main
    
    import "fmt"
    
    type Mutatable struct {
        a int
        b int
    }
    
    func (m Mutatable) StayTheSame() {
        m.a = 5
        m.b = 7
    }
    
    func (m *Mutatable) Mutate() {
        m.a = 5
        m.b = 7
    }
    
    func main() {
        m := &Mutatable{0, 0}
        fmt.Println(m)
        m.StayTheSame()
        fmt.Println(m)
        m.Mutate()
        fmt.Println(m)
    

    The output of the above program is :

    &{0 0}
    &{0 0}
    &{5 7}
    

提交回复
热议问题