This is a creation in Article, where the information may have evolved or changed. Welcome to the 26th chapter of [Golang Series Tutorial] (HTTPS://STUDYGOLANG.COM/SUBJECT/2). # # Go Support Object-oriented? Go is not a fully object-oriented programming language. The Go website's [FAQ] (https://golang.org/doc/faq#Is_Go_an_object-oriented_language) answers whether go is an object-oriented language, excerpt from the following. > can be said to be, or not. Although Go has types and methods that support object-oriented programming styles, there are no types of hierarchies. The "interface" concept in Go provides a different approach, which we think is easy to use and more common. Go can also nest structs, similar to subclasses (subclassing), but not exactly the same. In addition, Go provides features that are more generic than C + + or Java: Subclasses can be defined by any type of data, even built-in types such as simple "unboxed" integers. This is not constrained in structs (classes). In the next tutorial, we will discuss how to use Go to implement object-oriented programming concepts. Go has a lot of different features compared to other object-oriented languages like Java. # # using structs, rather than class go does not support classes, but rather provides [struct] (https://studygolang.com/articles/12263). A [method] (https://studygolang.com/articles/12264) can be added to the struct body. This binds the data and the methods of manipulating the data together to achieve similar effects to the class. For a deeper understanding, let's write an example. In the example, we create a custom [package] (https://studygolang.com/articles/11893), which helps us to better understand how the struct effectively replaces the class. Create a folder called ' Oop ' in your Go workspace. Create sub-folders ' Employee ' in ' opp ' again. Within ' employee ', create a file named ' Employee.go '. The folder structure would look like this: "Workspacepath, OOP, employee---Employee.go", replace the contents of ' Employee.go ' with the code shown below. "' Gopackage employeeimport (" FMT ") type EMployee struct {FirstName stringlastname stringtotalleaves intleavestaken int}func (e Employee) leavesremaining () {Fmt.P rintf ("%s%s has%d leaves remaining", E.firstname, E.lastname, (E.totalleaves-e.leavestaken))} "" In the above program, line 1th specifies that the file belongs to ' Employee ' package. The 7th Line declares an ' Employee ' structure. In line 14th, the struct ' Employee ' adds a method called ' leavesremaining '. This method calculates and displays the remaining number of leave for the employee. So now we have a struct and a method that binds the struct, which is similar to the class. Then create a file in the ' Oop ' folder, named ' Main.go '. Now the directory structure is as follows: "' Workspacepath, OOP, employee---Employee.go Workspacepath, OOP--main.go ' main.go ' The contents are as follows: "' Gopackage mainimport" Oop/employee "Func Main () {e: = employee. Employee {FirstName: "Sam", LastName: "Adolf", Totalleaves:30,leavestaken:20,}e.leavesremaining ()} "" We quoted in line 3rd Employee ' package. In ' Main () ' (line 12th), we call the ' Employee ' 's ' leavesremaining () ' method. This program cannot be run on Go playground because of a custom package. You can run in your local, enter the command ' Go install opp ' under ' Workspacepath/bin/oop ', the program will print output: ' ' Bashsam Adolf has ten leaves remaining ' ' # # Use New ( ) function, not the constructor the program we wrote above looks fine, but there are some details that need to beAttention. Let's see what happens when you define an ' employee ' struct variable with a value of 0. Modify the contents of ' Main.go ' to the following code: ' Gopackage mainimport ' Oop/employee ' func main () {var e employee. Employeee.leavesremaining ()} "' Our modification just creates a 0-value ' Employee ' struct variable (line 6th). The program outputs: ' ' Bashhas 0 leaves remaining ' you can see that the 0-value variable created with ' Employee ' is useless. It has no legal name and no reasonable leave details. In an OOP language like Java, a constructor is used to solve this problem. A legitimate object must be created using a parameterized constructor. Go does not support constructors. If a type of 0 value is not available, the programmer is required to hide the type and avoid direct access from other packages. Programmers should provide a function called ' NewT (Parameters) ' (https://studygolang.com/articles/11892) that initializes variables of type ' T ' as required. According to Go convention, the function that creates ' T ' type variable should be named ' NewT (Parameters) '. This is similar to the constructor. If a package contains only one type, according to Go, the function should be named ' New ' (parameters) instead of ' NewT (parameters) '. Let me change the original code so that it is available whenever you create an ' employee '. You should first make the ' employee ' struct non-referenced, and then create a ' New ' function that creates the ' employee ' struct variable. Enter the following code in ' Employee.go ': ' Gopackage employeeimport ("FMT") type employee struct {firstName stringlastname Stringtotalle Aves Intleavestaken Int}func New (firstName string, lastName string, Totalleave int, Leavestaken int) Employee {e: = Emplo Yee {firstName, lastName,Totalleave, Leavestaken}return E}func (E employee) leavesremaining () {fmt. Printf ("%s%s has%d leaves remaining", E.firstname, E.lastname, (E.totalleaves-e.leavestaken))} "" We made some important changes. We changed the first letter of the ' employee ' structure to lowercase ' e ', which is to change the ' type employee struct ' to ' type employee struct '. In this way, we change the ' employee ' structure to be unreferenced and prevent other packages from accessing it. Unless there is a special need, it is best practice to hide all the fields of all non-referenced structs. Since we do not need the ' employee ' field in the external package, we also make these fields inaccessible. Similarly, we have modified the method of ' leavesremaining () '. Now because ' employee ' is not referenced, it is not possible to create variables of type ' employee ' directly within other packages. So we provide a reference to the ' new ' function in line 14th, which takes the necessary parameters and returns a newly created ' employee ' struct variable. This program also requires some necessary modifications, but now run the program to understand the current changes. If you run the current program, the compiler will make an error as follows: "' Bashgo/src/constructor/main.go:6: Undefined:employee. Employee ' ' This is because we set ' employee ' to not be referenced, so the compiler will give an error, suggesting that the type is not defined in ' Main.go '. Perfect, as we expected, other packages cannot now easily create a 0 value ' employee ' variable. We managed to avoid creating an unusable ' employee ' struct variable. The only way to create an ' employee ' variable now is to use the ' New ' function. Modify the contents of ' Main.go ' as shown below. "' Gopackage main import" Oop/employee "Func Main () {e: = employee. New ("Sam", "Adolf", "Max") E.leavesremaining ()} "This file is onlyOne of the changes is line 6th. By passing the required variable to the ' new ' function, we created a new ' employee ' struct variable. The following is the contents of the modified two files. Employee.go ' Gopackage employeeimport ("FMT") type employee struct {firstName stringlastname stringtotalleaves Intleavestaken int}func New (firstName string, lastName string, Totalleave int, Leavestaken int) Employee {e: = employee { FirstName, LastName, Totalleave, Leavestaken}return E}func (E employee) leavesremaining () {fmt. Printf ("%s%s has%d leaves remaining", E.firstname, E.lastname, (E.totalleaves-e.leavestaken))} ' Main.go ' Gopackage Main import "Oop/employee" Func Main () {e: = employee. New ("Sam", "Adolf", "Ten,") E.leavesremaining ()} ' runs the program and outputs: ' Bashsam Adolf has leaves remaining ' ' Now you can understand that although Go does not support class, but structs can be a good substitute for classes, and a ' New (parameters) ' signature method can replace the constructor. This concludes with the classes and constructors in Go. Have a nice day. * * Previous tutorial-[Mutex] (https://studygolang.com/articles/12598) * * * Next tutorial-[combination replaces inheritance] (https://studygolang.com/articles/12680 )**
via:https://golangbot.com/structs-instead-of-classes/
Author: Nick Coghlan Translator: Noluye proofreading: polaris1119
This article by GCTT original compilation, go language Chinese network honor launches
This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove
2,066 Reads