Structs & Methods

Duration: 15 min•Difficulty: Hard•

A Struct is Go's way of creating custom data types that contain a collection of fields. It is similar to a Class in OOP languages (Java/PHP), but simpler without inheritance.

Methods

We can attach functions to a Struct, which are called Methods. This allows Structs to have behaviors.

When to use?

Use a Struct to represent real-world objects. Examples:

  • User (Name, Email, Password)
  • Product (Name, Price, SKU)
  • Car (Brand, Color, Year)
MAIN.GO
package main
import "fmt"
// Define a User Struct
type User struct {
Name string
Email string
Age int
}
// Method: A special function belonging to User
func (u User) SayHello() {
fmt.Println("Hello, my name is", u.Name)
}
func main() {
// Creating a new user object
user1 := User{
Name: "Raffi",
Email: "raffi@mail.com",
Age: 20,
}
fmt.Println("User Data:", user1)
// Calling the method
user1.SayHello()
}