Structs
Sample code link: https://repl.it/@jjoco/go-structs
Structs are analogous to classes in OOP languages. These are your user-defined types with their own fields.
Declaring a Struct
Use type and struct to declare a blueprint of your struct.
1 2 3 4 5 6 7 |
|
- Use of struct keyword instead of = when making a new type
- No classes or objects in Go
- No colon between field name and its type
Can declare outside calling file
Fortunately, one can declare a struct outside of a function that declares one without any extra import syntax, as long as they fall under the same package.
1 2 3 4 5 6 7 8 9 |
|
Using a Struct
Similar to creating a new class instance in OOP languages, a dev can create a new variable of your customized struct without extra keywords.
Syntax
1 2 3 4 5 6 7 |
|
- No use of new keyword
- Use of curly brackets {} instead of parentheses ()
- No colons when declaring type
- Fields within struct variable are initialized to their zero values without explicit assigning
Examples:
No input parameters
Fields within structs are zero-valued, if not defined at compile-time.
1 2 3 |
|
With input parameters
1 2 3 |
|
With input parameters specifically defined
1 2 3 4 5 6 7 8 9 10 11 |
|
Pointers and Structs
A dev can use a struct pointer similarly to any other pointer. They function similarly as well, as shown in the following Pass by Value and Pass by Pointer comparison.
Pass By Value
1 2 3 4 5 |
|
1 2 3 4 |
|
Pass By Pointer
1 2 3 4 5 |
|
1 2 3 4 |
|