Go doesn’t have classes like Java or C++. Instead they have something similar to a struct that the C language has. In fact, they even call it a struct
.
Unlike a class, where you encapsulate your data, having it private, instead here, the attribute data is all public. Secondly, the methods are not built into the struct, but something you add on.
Defining a Struct
Consider something like a student, where you want to store a series of properties about the student. You would create a struct like the following:
type Student struct {
Name string
Major string
GPA float32
}
Notice the use of the type
keyword, to let Go know you’re are creating a user defined type. Then you define the name for your type. Finally, you specify that you have a struct.
Inside of the struct, or within it parenthesis, you have each of the properties and the data type listed, one on each line. Although you do not have to do it that way. Consider the following:
type Vertex struct {
X, Y int
}
Adding a Method
In C++ we typically don’t use classes, and in C we can only use structs. However, we usually only use structs for data, not including a internal method, or pointer to a function, even though we can.
However, in Go, we can add a function to a struct, like you see here:
// Function to display the student's name and major
func (s Student) Display() {
fmt.Printf("Name: %s, Major: %s\n", s.Name, s.Major)
}
Notice, how we define the func
, then we specify that it’s to a Student
data-type, with a internal name for the function so we can make it easier to work with instance variables since there isn’t the concept of this
in Go.
Inside the function, we can use the temp name of the instance, to reference it’s variables.
Creating an Instance of a Struct
To create an instance of a struct, you use it like you’d use any other data-type, defining a var
, then the variable name, an equals ( =
), and then the struct name for the data-type with the values inside of braces.
type Vertex struct {
X, Y int
}
// Creating
var v = Vertex{1, 2}
var v = Vertex{X: 1, Y: 2} // Creates a struct by defining values
// with keys
Or you can define them intrinsically.
student := Student{
Name: "Alice Johnson",
Major: "Computer Science",
GPA: 3.8
}
Data Structs in a Different Package
If you have your struct in a different package, then you need to include that package in your app, and then reference the package.stuct name. Here is an example:
var v1 = extpackage.Vertex{1, 2}
var v2 = extpackage.Vertex{X: 1, Y: 2}
Notice how you can specify the properties if you want, otherwise it is the order of the properties, (which may not always be known/remembered).
Working with Structs in Go was originally found on Access 2 Learn