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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
