What is the difference between golang functions and methods?

WBOY
Release: 2024-04-25 12:51:02
Original
1107 people have browsed it

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
}
Copy after login

Call function:

result := sum(10, 20)
Copy after login

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 + "!"
}
Copy after login

Calling method:

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

Difference

##Definition##Scope Receiver Parameters Access type member##Actual case
CharacteristicsFunctionMethod
func
Global, Package Private Type Private
None Yes
NoYes

## 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))
}
Copy after login
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
}
Copy after login
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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template