1. How do you define a struct in Go?
Answer:
Explanation:
In Go, a struct is defined using the 'type' keyword followed by the struct name and the 'struct' keyword.
2. How do you instantiate a struct in Go?
Answer:
Explanation:
A struct in Go can be instantiated using 'var myStruct MyStruct', 'myStruct := new(MyStruct)', or 'myStruct := MyStruct{}'.
3. How do you access a field of a struct in Go?
Answer:
Explanation:
In Go, a field of a struct is accessed using the dot notation, e.g., 'myStruct.field'.
4. Can you compare two structs directly in Go?
Answer:
Explanation:
Two structs in Go can be compared directly using the '==' operator if they are of the same type and do not contain fields that are not comparable.
5. How do you declare a struct with embedded fields in Go?
Answer:
Explanation:
In Go, embedded fields in a struct are declared by specifying the type only, without a field name.
6. What is an anonymous struct in Go?
Answer:
Explanation:
An anonymous struct in Go is a struct that is defined without a name, usually declared and instantiated at the same time.
7. How do you initialize a struct with named fields in Go?
Answer:
Explanation:
In Go, a struct can be initialized with named fields using the syntax 'MyStruct{fieldName: value}'.
8. Can structs in Go have methods associated with them?
Answer:
Explanation:
In Go, methods can be defined on structs. A method is a function with a special receiver argument.
9. What is the purpose of the 'tag' in a struct field in Go?
Answer:
Explanation:
Tags in Go struct fields provide metadata that can be accessed using reflection, often used for things like encoding/decoding to JSON, XML, etc.
10. How can you ensure a struct field is not exported outside a package in Go?
Answer:
Explanation:
In Go, a field name that starts with a lowercase letter is not exported outside the package.
11. How do you embed an interface in a struct in Go?
Answer:
Explanation:
In Go, you can embed an interface in a struct by specifying the interface type only, without a field name.
12. Can a struct in Go inherit fields from another struct?
Answer:
Explanation:
Go does not have inheritance, but you can achieve a similar effect by embedding one struct type into another.
13. How do you pass a struct to a function in Go?
Answer:
Explanation:
In Go, structs can be passed to functions either by value or by reference (using a pointer).
14. Is it possible to have a struct with no fields in Go?
Answer:
Explanation:
In Go, it is perfectly valid to define a struct with no fields, often used for method grouping.
15. How do you update a field of a struct passed by reference to a function in Go?
Answer:
Explanation:
In Go, when you have a pointer to a struct, you can update its fields directly using the '.' operator, without needing to dereference it explicitly.