Structs
Intermediate · Types & Methods
A struct groups named fields into a composite type. Construct with field names
(T{Field: v}), access with a dot. Go favors composition via embedding
(declaring a type without a field name) over inheritance, and you attach
behavior with methods.
Resources
Section titled “Resources”Exercises
Section titled “Exercises”structs1 compile
Section titled “structs1 compile”Define the struct’s fields.
Show hint
Structs are created using the `type structName struct {}` syntax.Fields inside the brackets must have their types declared along with their names.structs2 compile
Section titled “structs2 compile”Embed a struct instead of adding a plain field.
Show hint
Embedding a struct is done using just the struct name.
After embedding, fields can be accessed directly through the base struct without specifying the full path, but you can if needed.structs3 compile
Section titled “structs3 compile”Attach a method to a struct.
Show hint
Add a function to a struct by defining it as follows:
func (s *StructHere) doSomething() {
}