Go is a popular programming language, some of which have external visibility methods, that is, exported methods. Exported methods can be called by other packages or files, while private methods can only be used internally. In this article, we will discuss the concept of exported methods in Golang, how to export methods and some tips for using exported methods.
The concept of exported methods
In Golang, only methods starting with a capital letter will be called by other packages and files. This means that if a method's name starts with a lowercase letter, it will be considered a private method. These private methods are only accessible within files within the same package. Therefore, in order to make the method available in other packages or files, we need to change the first letter of the method name to uppercase.
How to export methods
Here is a sample code to demonstrate how to export methods:
package main import "fmt" type Student struct { Name string Age int } func (s Student) PrintAge() { fmt.Printf("%s is %d years old\n", s.Name, s.Age) } func main() { student := Student{"Alice", 21} student.PrintAge() }
In the above code, we define a structure called Student body and defines a method named PrintAge. Since PrintAge's name starts with a capital letter P, this means it can be called by other packages or files. In the main function, we create an instance named student and then call the PrintAge method to print its age.
Tips for using exported methods
The following are some tips for using exported methods:
Summary
In this article, we discussed the concept of exported methods, how to export methods, and tips for using exported methods. By using exported methods, we can avoid defining duplicate types, implement interfaces, provide APIs, and easily test the code. If you are using the Golang programming language and want to make a method visible and used in other packages or files, make sure to change the first letter of the method name to an uppercase letter.
The above is the detailed content of Discuss the techniques of exporting methods in Golang. For more information, please follow other related articles on the PHP Chinese website!