Structs and Methods
Create custom data types using structs and attach behavior using methods.
Learning objective: Create a struct and define a method for it.
Structs
A struct groups related fields together. It is useful for representing real-world objects such as students, books, products, and customers.
Creating Struct Values
You can create a struct value by providing values for its fields.
Methods
A method is a function attached to a type. Methods help you organize behavior around the data it belongs to.
Example Code
Create or update your Go file, then run the program using go run main.go.
package main
import "fmt"
type Student struct {
Name string
Score int
}
func (s Student) Display() {
fmt.Println(s.Name, "scored", s.Score)
}
func main() {
student := Student{Name: "Ali", Score: 88}
student.Display()
}
Key points to remember
- Struct field names usually use capital letters when they need to be exported.
- Methods can use value receivers or pointer receivers.
- Structs are important for building larger Go programs.
Practice Exercises
- Create a Book struct.
- Create a method to display book details.
- Create three struct values and print them.
Continue Learning
After this lesson, continue to the next lesson or explore related tutorials on VisualStudioTutor.com.