Home > Article > Backend Development > What is the difference between the access restrictions of golang methods and functions?
Access control in Go is specified by name prefix characters: Method access control: public (uppercase): accessible to all packages private (lowercase): accessible only to the package that defines it Function access control: public (uppercase): all packages Accessible package (lowercase): Only the package that defines it is accessible
Access restrictions on methods and functions in Go
In In Go language, the access permissions of variables, methods and functions are determined by the prefix characters of their names.
Method access control
Methods are functions associated with the structure type. They are prefixed with the following characters:
public
(capital letters): accessible in all packages. private
(lowercase letters): Accessible only within the package in which it is defined. Example:
type Person struct { name string } // public 方法 func (p Person) PublicMethod() { // ... } // private 方法 func (p Person) privateMethod() { // ... }
Function access control
Similar to methods, the prefix character of the function is also determined Their access rights:
public
(capital letters): accessible in all packages. package
(lowercase letters): Accessible only within the package in which it is defined. Example:
// public 函数 func PublicFunction() { // ... } // package 函数 func packageFunction() { // ... }
Practical case
Suppose we have a packagecustomer
, which defines a Customer
structure and a public method GetFullName
:
package customer type Customer struct { firstName string lastName string } // public 方法 func (c Customer) GetFullName() string { return c.firstName + " " + c.lastName }
In another package main
, we can use# The Customer
type and GetFullName
method in the ##customer package:
package main import ( "fmt" "customer" ) func main() { c := customer.Customer{ firstName: "John", lastName: "Doe", } fullName := c.GetFullName() fmt.Println(fullName) // 输出:John Doe }
The above is the detailed content of What is the difference between the access restrictions of golang methods and functions?. For more information, please follow other related articles on the PHP Chinese website!