()
| 24 | } |
| 25 | |
| 26 | func main() { |
| 27 | |
| 28 | // This syntax creates a new struct. |
| 29 | fmt.Println(person{"Bob", 20}) |
| 30 | |
| 31 | // You can name the fields when initializing a struct. |
| 32 | fmt.Println(person{name: "Alice", age: 30}) |
| 33 | |
| 34 | // Omitted fields will be zero-valued. |
| 35 | fmt.Println(person{name: "Fred"}) |
| 36 | |
| 37 | // An `&` prefix yields a pointer to the struct. |
| 38 | fmt.Println(&person{name: "Ann", age: 40}) |
| 39 | |
| 40 | // It's idiomatic to encapsulate new struct creation in constructor functions |
| 41 | fmt.Println(newPerson("Jon")) |
| 42 | |
| 43 | // Access struct fields with a dot. |
| 44 | s := person{name: "Sean", age: 50} |
| 45 | fmt.Println(s.name) |
| 46 | |
| 47 | // You can also use dots with struct pointers - the |
| 48 | // pointers are automatically dereferenced. |
| 49 | sp := &s |
| 50 | fmt.Println(sp.age) |
| 51 | |
| 52 | // Structs are mutable. |
| 53 | sp.age = 51 |
| 54 | fmt.Println(sp.age) |
| 55 | |
| 56 | // If a struct type is only used for a single value, we don't |
| 57 | // have to give it a name. The value can have an anonymous |
| 58 | // struct type. This technique is commonly used for |
| 59 | // [table-driven tests](testing-and-benchmarking). |
| 60 | dog := struct { |
| 61 | name string |
| 62 | isGood bool |
| 63 | }{ |
| 64 | "Rex", |
| 65 | true, |
| 66 | } |
| 67 | fmt.Println(dog) |
| 68 | } |
nothing calls this directly
no test coverage detected