Project 14: Profile viewer

Nemuel Wainaina
2 min readOct 1, 2024

--

Complete video course: Udemy

Introduction

Profile viewer is a rudimentary project only intended to help us get more comfortable working with structs. We shall define a Person struct containing 3 fields: Name, Age, and Email. After that, we shall create 2 instances of this struct and display this information.

Practical

Boilerplate code:

package main

import (

)

func main() {

}

Let us import the fmt package which is all we need for this project:

import (
"fmt"
)

Next, let us define the Person struct containing the 3 fields:

type Person struct {
Name string
Age int
Email string
}

Once that is done, we can move to our main function and create 2 instances of the struct:

person1 := Person{Name: "Bob", Age: 30, Email: "bob@example.com"}
person2 := Person{Name: "Alice", Age: 40, Email: "alice@example.com"}

As shown in the above snippet, we have the struct name followed by key-value pairs within curly braces. The dot notation can also be used to both set and get field values in a struct eg. person1.Age = 50.

Now, that we have initialized the 2 instances of type Person, we can create a function that will display this information to the user in a nice format:

func displayInformation(p Person) {
fmt.Println("Profile information:")
fmt.Printf("Name: %s\n", p.Name)
fmt.Printf("Age: %d\n", p.Age)
fmt.Printf("Email: %s\n", p.Email)
fmt.Println()
}

The above function takes in an argument of type Person (struct types can be passed to and returned from functions just like the other types). Inside the function, we access and display the field values (name, age, and email) using the dot notation. Finally, we call the Println() function with no argument to print a blank line.

We can call this function in the main function to display the values contained in the 2 instances:

displayInformation(person1)
displayInformation(person2)

Complete code:

package main

import (
"fmt"
)

type Person struct {
Name string
Age int
Email string
}

func displayInformation(p Person) {
fmt.Println("Profile information:")
fmt.Printf("Name: %s\n", p.Name)
fmt.Printf("Age: %d\n", p.Age)
fmt.Printf("Email: %s\n", p.Email)
fmt.Println()
}

func main() {
person1 := Person{Name: "Bob", Age: 30, Email: "bob@example.com"}
person2 := Person{Name: "Alice", Age: 40, Email: "alice@example.com"}

displayInformation(person1)
displayInformation(person2)
}

Next: Project 15: To-Do list app

--

--

Nemuel Wainaina
Nemuel Wainaina

Written by Nemuel Wainaina

Security Researcher | Software Engineer

No responses yet