Go Structs Example

Go’s structs are typed collections of fields. They’re useful for grouping data together to form records.

Go struct definition

A struct is defined with the type keyword:

type User struct {
    firstName       string
    lastName string
    email        string
}

Go Structs Example

The following is a Go struct simple example.


package main

import "fmt"

type User struct {
    firstName    string
    lastName     string
    email        string
}

func main() {

    u := User{"John", "Cena", "john@gmail.com"}

     // print user structure
     fmt.Println(u)

     // The struct fields are accessed with the dot operator.
     fmt.Println(u.firstName)
     fmt.Println(u.lastName)
     fmt.Println(u.email)
}

Output:

{John Cena john@gmail.com}
John
Cena
john@gmail.com

Comments