Home  >  Article  >  Backend Development  >  What is the difference between the access restrictions of golang methods and functions?

What is the difference between the access restrictions of golang methods and functions?

王林
王林Original
2024-04-26 15:12:02429browse

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

golang 方法和函数的访问限制有什么区别?

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!

Statement:
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