Home > Backend Development > Golang > The evolution of golang function naming convention

The evolution of golang function naming convention

PHPz
Release: 2024-05-01 15:24:01
Original
708 people have browsed it

The evolution of Golang function naming convention is as follows: Early stage (Go 1.0): No formal convention, use camel naming. Underscore convention (Go 1.5): Exported functions start with a capital letter and are prefixed with an underscore. Factory function convention (Go 1.13): Functions that create new objects are represented by the "New" prefix.

The evolution of golang function naming convention

The evolution of Golang function naming convention

Golang function naming convention continues to evolve over time, aiming to improve code readability and consistency and maintainability.

Early Stages (Go 1.0)

Initially, Golang had no formal function naming convention. Function names usually consist of camel naming without an underscore prefix, for example:

func MyFunction() {
    // ...
}
Copy after login

Underscore Convention (Go 1.5)

Go 1.5 introduced the underscore convention, requiring exports Functions start with a capital letter and are prefixed by an underscore. This helps distinguish public API functions from non-exported functions:

func MyPublicFunction() {
    // ...
}

func _myPrivateFunction() {
    // ...
}
Copy after login

Factory Function Conventions (Go 1.13)

Go 1.13 adds a factory function naming convention. These functions are used to create new objects and are represented by the "New" prefix:

func NewMyObject() *MyObject {
    // ...
}
Copy after login

Practical example

The following is a piece of code that shows the practical application of these conventions:

package main

func main() {
    myPrivateFunction() // 非导出函数,以 "_" 前缀开头
    myPublicFunction() // 公共 API 函数,以大写字母开头并以下划线前缀

    // 创建新对象
    myObject := NewMyObject()

    // 使用对象的方法
    myObject.MyObjectMethod()
}

func _myPrivateFunction() {
    // ...
}

func MyPublicFunction() {
    // ...
}

type MyObject struct {
    // ...
}

func (o *MyObject) MyObjectMethod() {
    // ...
}
Copy after login

By following these conventions, we can enhance the clarity and consistency of Golang code.

The above is the detailed content of The evolution of golang function naming convention. 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