Home >Backend Development >Golang >What is the difference between golang functions and methods?

What is the difference between golang functions and methods?

WBOY
WBOYOriginal
2024-04-25 12:51:021157browse

Functions and methods are two ways to define code blocks in Go. Function scope is global or package private, and method scope is type private. Functions do not have receiver parameters, whereas methods have receiver parameters that allow access to type members. The practical case shows the average calculation function without using a structure, and the weighted average calculation method using a structure.

golang 函数与方法的区别是?

The difference between functions and methods in Go

Introduction
In the Go language, functions and methods are two ways of defining code blocks. While there are many similarities, they also have fundamental differences. This article will dive into the differences between functions and methods in Go and provide practical examples.

Function
A function is a type-independent block of code that performs some operation on input and returns output. Functions are defined using the func keyword, followed by the function name, parameter list, and return value type.

Example:

func sum(a, b int) int {
    return a + b
}

Call function:

result := sum(10, 20)

Method
Method is appended to a function on the type. It allows instances of the type to access and manipulate the method's implementation. Methods are defined using receiver parameters, followed by the method name, parameter list, and return value type.

Example:

type Person struct {
    Name string
}

func (p Person) Greet() string {
    return "Hello, " + p.Name + "!"
}

Calling method:

p := Person{"John"}
greeting := p.Greet()

Difference

##Definition##Scope Receiver Parameters Access type member##Actual case
Characteristics Function Method
func afbca75a3c4bea07d39946edd0d57a61 a4e733488ff4d79deacc65b80d12a259
Global, Package Private Type Private
None Yes
No Yes

## Calculate the average

Without using a structure, you can write a function to calculate the average of an array of floating point numbers:

func Avg(numbers []float64) float64 {
    sum := 0.0
    for _, num := range numbers {
        sum += num
    }
    return sum / float64(len(numbers))
}
Calculate the weighted average

If you need to calculate the average based on the weight, you can use a method:

type WeightedAvg struct {
    Numbers []float64
    Weights []float64
}

func (w WeightedAvg) Avg() float64 {
    weightedSum := 0.0
    for i := range w.Numbers {
        weightedSum += w.Numbers[i] * w.Weights[i]
    }
    totalWeight := 0.0
    for _, w := range w.Weights {
        totalWeight += w
    }
    return weightedSum / totalWeight
}
Conclusion

Functions and methods play different roles in the Go language. Functions are type-independent blocks of code that perform common tasks. Methods are functions attached to a type that are used to manipulate and access instances of that type. Understanding the difference between functions and methods is critical to writing clear, maintainable Go code.

The above is the detailed content of What is the difference between golang functions and methods?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn