SoFunction
Updated on 2025-03-05

Analysis on the difference between ordinary functions and methods in Go language

package structTest 
 
//The difference between ordinary functions and methods (when the receivers are value type and pointer type respectively)
//Date:2014-4-3 10:00:07 
 
import ( 
    "fmt" 

 
func StructTest06Base() { 
    structTest0601() 
    structTest0602() 

 
//1. Ordinary functions
// Function that receives value type parameters
func valueIntTest(a int) int { 
    return a + 10 

 
// Functions that receive pointer type parameters
func pointerIntTest(a *int) int { 
    return *a + 10 

 
func structTest0601() { 
    a := 2 
    ("valueIntTest:", valueIntTest(a)) 
//The parameter of the function is of value type, so the pointer cannot be passed directly as a parameter.
    //("valueIntTest:", valueIntTest(&a)) 
    //compile error: cannot use &a (type *int) as type int in function argument 
 
    b := 5 
    ("pointerIntTest:", pointerIntTest(&b)) 
//Similarly, when the parameter of a function is a pointer type, the value type cannot be directly passed as a parameter.
    //("pointerIntTest:", pointerIntTest(b)) 
    //compile error:cannot use b (type int) as type *int in function argument 

 
//2. Method
type PersonD struct { 
    id   int 
    name string 

 
//The receiver is the value type
func (p PersonD) valueShowName() { 
    () 

 
//The receiver is pointer type
func (p *PersonD) pointShowName() { 
    () 

 
func structTest0602() { 
//Value type call method
    personValue := PersonD{101, "Will Smith"} 
    () 
    () 
 
//Pointer type call method
    personPointer := &PersonD{102, "Paul Tony"} 
    () 
    () 
 
//Unlike ordinary functions, the receiver is a method of pointer type and value type, and variables of pointer type and value type can be called from each other.
}