Home > Article > Backend Development > The evolution of golang function naming convention
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.
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() { // ... }
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() { // ... }
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 { // ... }
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() { // ... }
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!