Home > Backend Development > Golang > golang structure method

golang structure method

PHPz
Release: 2023-04-21 15:16:32
Original
157 people have browsed it

Golang is an efficient programming language, and its structure method is one of the features worth mentioning in Golang. Golang uses structures to organize data, and structure methods are functions that operate on the data in the structure. This article will introduce you to the concepts, syntax and examples of Golang structure methods.

1. Overview of Golang structure methods

In Golang, a structure represents a user-defined type that can combine different types of data. The data contained in a structure is called fields. A structure method is a function related to a structure that can modify and manipulate the data and fields in the structure type value. Struct methods in Golang are similar to class methods in object-oriented programming, but there are some differences in syntax.

The following is an example, defining a person structure with two fields: name and age, and defining a greet() method:

<code class="go">type person struct {
    name string
    age int
}

func (p person) greet() {
    fmt.Printf("Hello, my name is %s and I am %d years old\n", p.name, p.age)
}</code>
Copy after login

In this example, Golang is used Method declaration syntax, which starts with the func keyword, followed by parentheses in which the receiver is defined, followed by the method name and method body. Here, the receiver is a value of type person, which is named p. The method name is greet(), it does not require any parameters, and a greeting is printed in the method body.

2. The syntax of Golang structure method

The structure method definition in Golang contains three important parts:

  • Method receiver
  • Method name
  • Method body

Among them, the method receiver is required, which is used to specify the structure type of the receiving method. There are two method receiver types.

  • Value receiver
  • Pointer receiver

In the value receiver, the method receiver is the value of the structure type. When a method is called on a receiver, a copy of the receiver is created and the method is executed on that copy. In this case, the value of the structure is used, not a pointer to the value. This method can query data in the structure, but cannot change the value of the structure.

In pointer receivers, the method receiver is a pointer of structure type. When the method is called on the receiver, the method is executed on this pointer. In this case, the pointer to the structure is used, not the value of the structure. This method can query and modify data in the structure.

The following is an example of two method receivers:

<code class="go">type person struct {
    name string
    age int
}

// 值接收者方法
func (p person) Greet() {
    fmt.Printf("Hello, my name is %s and I am %d years old\n", p.name, p.age)
}

// 指针接收者方法
func (p *person) SetAge(age int) {
    p.age = age
}</code>
Copy after login

In this example, the first method Greet() uses a value receiver, and the second method SetAge() uses Pointer receiver.

Note: Using a value receiver or a pointer receiver depends on the actual scenario. Generally speaking, when you need to modify the value of a structure, it is more appropriate to use a pointer receiver; when you only need to obtain the structure When using a value, just use the value receiver.

3. Examples of Golang structure methods

The following uses practical examples to show how to use Golang structure methods.

1. Value receiver method

<code class="go">package main

import "fmt"

type Rectangle struct {
    width, height float64
}

func (r Rectangle) Area() float64 {
    return r.width * r.height
}

func (r Rectangle) Perimeter() float64 {
    return 2 * (r.width + r.height)
}

func main() {
    rect := Rectangle{width: 10, height: 5}
    fmt.Println("Area of rectangle:", rect.Area())
    fmt.Println("Perimeter of rectangle:", rect.Perimeter())
}</code>
Copy after login

Output:

<code>Area of rectangle: 50
Perimeter of rectangle: 30</code>
Copy after login

In this example, we define a Rectangle structure, which has two fields: width and height. Then, we implemented two methods: Area() method and Perimeter() method. The Area() method calculates the area of ​​a rectangle, and the Perimeter() method calculates the perimeter of a rectangle. Both methods use value receivers because they only query the value of the rectangle and do not modify it.

2. Pointer receiver method

<code class="go">package main

import "fmt"

type Rectangle struct {
    width, height float64
}

func (r *Rectangle) Area() float64 {
    return r.width * r.height
}

func (r *Rectangle) Perimeter() float64 {
    return 2 * (r.width + r.height)
}

func (r *Rectangle) Resize(width, height float64) {
    r.width += width
    r.height += height
}

func main() {
    rect := Rectangle{width: 10, height: 5}
    fmt.Println("Area of rectangle:", rect.Area())
    fmt.Println("Perimeter of rectangle:", rect.Perimeter())

    rect.Resize(5, 5)
    fmt.Println("After resizing:")
    fmt.Println("Area of rectangle:", rect.Area())
    fmt.Println("Perimeter of rectangle:", rect.Perimeter())
}</code>
Copy after login

Output:

<code>Area of rectangle: 50
Perimeter of rectangle: 30
After resizing:
Area of rectangle: 100
Perimeter of rectangle: 40</code>
Copy after login

In this example, we also define a Rectangle structure and two methods: Area() and Perimeter(). However, here we also implement the Resize() method, which uses a pointer receiver to allow us to modify the value of the Rectangle structure. In the main() function, we create a Rectangle structure and use Area() and Perimeter() to calculate the area and perimeter of the rectangle. We then scaled the rectangle using the Resize() method and calculated the area and perimeter again.

4. Summary

The structure method in Golang can help us operate the values ​​of structure types more effectively. Using the structure method, we can combine operations and data to write clearer and more concise programs. The receiver of a method can be a value or pointer of a structure type, and different receiver types can be selected as needed. In addition, you can also add parameters and return values ​​to methods, chain calls to multiple methods in method calls, and so on. It is worth noting that in the method declaration, the space between the receiver type and the method name must exist, otherwise it will cause a compilation error. In practical applications, we need to choose the appropriate receiver type according to the actual situation, and flexibly use various methods to handle different data operations.

The above is the detailed content of golang structure method. For more information, please follow other related articles on the PHP Chinese website!

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