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

How to distinguish golang functions and methods?

WBOY
Release: 2024-04-25 15:09:02
Original
885 people have browsed it

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

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

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

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!

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