Struct और Interface

Go Structs

Group related values into your own type with named fields.

  • मध्यम
  • 3 मिनट में पढ़ें
  • 1 चलाने योग्य उदाहरण
आप क्या सीखेंगे
  • Defining a struct
  • Fields and %+v
  • Structs are copied
User
Name"Ada"
Age37
Activetrue

Your own type with named fields

A struct is a type you define by naming its fields. It keeps related data together, such as the name, age and status of a user.

Fields are read and changed with a dot. %v prints the values and %+v adds the field names. Assigning a struct copies it, so changing guest does not change user. A struct can also be declared in place without a name.

मुख्य बातें

  1. Fields are read and changed with a dot.
  2. %+v prints the field names too.
  3. Assigning a struct copies it.

चलने योग्य Go उदाहरण

Go
कोड चलाएँ →
main.go
package main

import "fmt"

type User struct {
	Name   string
	Age    int
	Active bool
}

func main() {
	user := User{Name: "Ada", Age: 36, Active: true}
	user.Age++

	fmt.Println(user.Name, user.Age)
	fmt.Printf("%v\n%+v\n", user, user)

	guest := user // structs are copied on assignment
	guest.Name = "Guest"
	fmt.Println(user.Name, guest.Name)

	point := struct{ X, Y int }{3, 4}
	fmt.Println(point.X + point.Y)
}
इस उदाहरण के लिए Run बटन बनाएँ कोड चलाने का परिणाम
Ada 37
{Ada 37 true}
{Name:Ada Age:37 Active:true}
Ada Guest
7

अभ्यास

उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।

यह पाठ पूरा कर लिया?

अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।

चैलेंज से अभ्यास करें

इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।

सभी चैलेंज