Structs and methods

Knowledge Videos

Short animated explainers, organised by subject.

Structs and methods

A struct groups named, typed fields into your own type, a method is a function that belongs to a type, and a pointer receiver changes the real value instead of a copy.

Try it

Transcript

A struct groups named fields into your own type. A Pet struct might have a name, an age and a hunger level. It is like a form to fill in, where every field has a type.

You make a value of that type by filling in the fields, and you read a field with a dot, like p dot Name.

A method is a function that belongs to a type. You write the type in brackets before the name. Now p dot Describe runs the method on that pet.

If a method should change the real pet, use a pointer receiver, with a star. Without the star, the method works on a copy, and the real pet does not change.

Remember: a struct is your own type made of fields, a method is a function that belongs to a type, and a pointer receiver changes the real value.

More in this series