Structs
Ek struct related fields ko ek naam wale type ke neeche group karta hai — Go mein classes nahi hain, isliye ek struct plus uske associated functions (agle lesson mein cover kiya gaya) hi ek "cheez" ko data ke saath model karne ka tarika hai.
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
alice := Person{Name: "Alice", Age: 30}
fmt.Println(alice.Name, "is", alice.Age, "years old")
}Alice is 30 years old
Structs values hote hain
Ek struct ko assign ya pass karna default roop se use copy kar deta hai — rect.Width = 12 sirf main mein local rect variable ko change karta hai, kahin aur kisi shared instance ko nahi. Ek struct ko directly Println se print karna uske saare field values order mein dikhata hai.
package main
import "fmt"
type Rectangle struct {
Width, Height float64
}
func main() {
rect := Rectangle{Width: 10, Height: 5}
rect.Width = 12
fmt.Println(rect)
}{12 5}Aage: methods — receivers ke saath ek struct mein behavior attach karna.
Practice exercise
Ek struct Book define karo jiske fields Title string aur Pages int hon. Title "Dune" aur Pages 412 wali ek book banao, phir book.Title aur book.Pages ko fmt.Println(book.Title, book.Pages) se print karo.