Home > Backend Development > Golang > golang add method

golang add method

王林
Release: 2023-05-19 09:09:07
Original
579 people have browsed it

Golang is a popular programming language widely used in the web and cloud computing fields. Methods are one of the important concepts when writing Golang programs. This article will introduce how to add methods in Golang.

First, let’s look at a simple structure (struct) example.

type Student struct {
    Name    string
    Age     int
    Grade   int
}
Copy after login

This structure represents a student and contains attributes such as name, age, and grade. Next, we need to add methods to this structure.

Methods in Golang refer to a set of functions that act on variables of a specific type. When defining a method in a structure, you need to specify the name of the structure variable before the function name.

The following is an example of adding a method to the Student structure:

func (s *Student) GetInfo() string {
    return "Name: " + s.Name + ", Age: " + strconv.Itoa(s.Age) + ", Grade: " + strconv.Itoa(s.Grade)
}
Copy after login

In this example, we add a GetInfo() method to the Student structure. This method returns the student's basic information string, including name, age and grade information. The keyword "func" represents a function declaration. The "s *Student" in the brackets means that s is a pointer to the Student type. We can access the properties in the Student through s in this method. Here, we use the Itoa (integer to ASCII) function to convert the integer Age and Grade to strings.

Next, let’s take a look at how to use this newly added method. Create a new student instance in the main function and obtain its basic information through this method.

func main() {
    s := Student{
        Name:   "John",
        Age:    18,
        Grade:  12,
    }
    info := s.GetInfo()
    fmt.Println(info)
}
Copy after login

The above code creates a student named "John", who is 18 years old and in grade 12. Then, we called the GetInfo() method and assigned its return value to the variable info. Finally, the student's basic information is output to the console.

Method is a very important concept when writing programs in Golang. Adding methods enables a structure to have its own behavior and operations. I hope this article will help you understand the adding methods in Golang.

The above is the detailed content of golang add 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