Methods in Go (Let's Go twenty-four)

1. Method definition

GoA method is a special kind of function that, by 接受者binding 函数together, can emulate object-oriented behavior.

func (a constru) funName(para paraType,[para2 paraType]) (returnType,[returnType2]) {
    
    
    
}

To bind a function to a type, simply prefix the function name with the type to be bound.

package main

import (
	"fmt"
)

type site struct {
    
    
	name string
	age  int
}

func (s *site) show() string {
    
    
	s.name = "https://qiucode.cn"
	return s.name
}

func main() {
    
    

	web := site{
    
    }
	str := web.show()
	
	fmt.Println(stra)
}

insert image description here

2. Basic type binding function

package main

import (
	"fmt"
)

type intArray []int //定义一个新类型

func (arr *intArray) sum() (sum int) {
    
    
	for _, num := range *arr {
    
    
		sum += num
	}
	return
}

func main() {
    
    

	num := intArray{
    
    3, 4, 5}
	total := num.sum()

	fmt.Println(total)
}

insert image description here

Guess you like

Origin blog.csdn.net/coco2d_x2014/article/details/127416433
Go