Go by Example: Structs

A struct is a composite data type in Go that allows you to group together values of different types under a single name. Structs can be used to represent objects and data structures.

Here’s an example of how to define and use a struct in Go:

package main

import "fmt"

type person struct {
	name string
	age  int
}

func main() {
	p := person{name: "John Doe", age: 30}

	fmt.Println("Name:", p.name)
	fmt.Println("Age:", p.age)
}

Output:

Name: John Doe
Age: 30

In this example, we defined a person struct type with two fields: name and age. Then, we created an instance of person and assigned values to its fields. We accessed the fields using dot notation (e.g. p.name and p.age).

You can also create a pointer to a struct:

package main

import "fmt"

type person struct {
	name string
	age  int
}

func main() {
	p := &person{
		name: "John Doe",
		age:  30,
	}

	fmt.Println("Name:", p.name)
	fmt.Println("Age:", p.age)
}

Output:

Name: John Doe
Age: 30

In this example, we created a pointer to a person struct by using the address-of operator &. To access the fields of the struct, we used the -> operator instead of the dot operator.

You can also embed one struct type into another struct type to create a nested struct:

package main

import "fmt"

type address struct {
	street string
	city   string
	state  string
}

type person struct {
	name    string
	age     int
	address address
}

func main() {
	p := person{
		name: "Jane Doe",
		age:  25,
		address: address{
			street: "123 Main St",
			city:   "New York",
			state:  "NY",
		},
	}

	fmt.Println("Name:", p.name)
	fmt.Println("Age:", p.age)
	fmt.Println("Address:", p.address.street, p.address.city, p.address.state)
}

Output:

Name: Jane Doe
Age: 25
Address: 123 Main St New York NY

In this example, we embedded the address struct type into the person struct type. To access the fields of the embedded struct, we used dot notation (e.g. p.address.street, p.address.city, and p.address.state).


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *