go / beginner
Snippet
Defining Custom Types with Structs
Structs are composite types that group together related fields. You define a struct using the `type` keyword, then create instances with brace initialization. Methods can be attached to structs using a receiver - here `(r Rectangle)` means the method belongs to Rectangle values. Pointers to structs are useful for mutation and are automatically dereferenced when accessing fields.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package mainimport "fmt"type Rectangle struct {Width float64Height float64}func (r Rectangle) Area() float64 {return r.Width * r.Height}func main() {rect := Rectangle{Width: 10.5, Height: 4.2}fmt.Printf("Area: %.2f\n", rect.Area())ptr := &rectfmt.Printf("Width via pointer: %.2f\n", ptr.Width)}
Breakdown
1
type Rectangle struct {
Defines a new struct type with Width and Height fields
2
func (r Rectangle) Area() float64 {
Method with value receiver attached to Rectangle
3
rect := Rectangle{Width: 10.5, Height: 4.2}
Creates instance using named field initialization
4
ptr := &rect
Creates a pointer to the rectangle
5
ptr.Width
Go automatically dereferences pointer to access field