Golang / GoLang Basics Interview Questions
How do structs work in Go and how do you attach methods to them?
Structs are Go's primary mechanism for grouping related data. Methods are functions with a receiver — the type they are attached to. The receiver can be a value or a pointer, which changes whether the method can modify the struct.
type Person struct { FirstName string LastName string Age int email string // unexported } // Creating struct instances p1 := Person{FirstName: "Alice", LastName: "Smith", Age: 30} p2 := &Person{FirstName: "Bob", Age: 25} // pointer to struct // Value receiver â works on a copy; cannot modify the original func (p Person) FullName() string { return p.FirstName + " " + p.LastName } // Pointer receiver â modifies the original struct func (p *Person) HaveBirthday() { p.Age++ } fmt.Println(p1.FullName()) // Alice Smith p1.HaveBirthday() // Go auto-takes address: (&p1).HaveBirthday() fmt.Println(p1.Age) // 31 // Anonymous struct â useful for one-off data grouping point := struct{ X, Y int }{X: 3, Y: 7} // Struct embedding â promotes fields and methods (composition) type Employee struct { Person // embedded â promotes Name, HaveBirthday, etc. Company string Salary float64 } e := Employee{Person: Person{FirstName: "Carol", Age: 28}, Company: "Acme"} fmt.Println(e.FullName()) // Carol â promoted method
More Related questions...