Home  >  Article  >  Backend Development  >  How to distinguish golang functions and methods?

How to distinguish golang functions and methods?

WBOY
WBOYOriginal
2024-04-25 15:09:02845browse

The difference between Go functions and methods is that the function is defined outside the package and does not receive a receiver; while the method is defined within the type and receives the type receiver as the first parameter.

如何区分 golang 函数和方法?

#How to distinguish between Go functions and methods?

In the Go language, although functions and methods look similar, there are essential differences between them.

Function

  • is defined outside the package scope and can be called directly.
  • Does not accept type receivers.
func Greet(name string) string {
    return "Hello, " + name + "!"
}

Method

  • is defined within the type and can only be called through type instances.
  • Receive type receiver as first parameter.
type Person struct {
    Name string
}

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

Practical case

The following code demonstrates the difference between functions and methods:

package main

import "fmt"

func main() {
    // 调用函数
    greeting1 := Greet("Alice")
    fmt.Println(greeting1) // 输出:Hello, Alice!

    // 实例化类型并调用方法
    alice := Person{Name: "Alice"}
    greeting2 := alice.Greet()
    fmt.Println(greeting2) // 输出:Hello, Alice!
}

func Greet(name string) string {
    return "Hello, " + name + "!"
}

type Person struct {
    Name string
}

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

The above is the detailed content of How to distinguish 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